Renato
Renato

Reputation: 345

Separate list in equal steps

I have a list of variable size. She will always have at least three elements, and new elements are always multiples of three.

An example list would be as follows:

['ttyUSB0', 'ttyUSB1', 'ttyUSB2', 'ttyUSB3', 'ttyUSB4',
'ttyUSB5', 'ttyUSB6', 'ttyUSB7', 'ttyUSB8']

My problem is I always have to pick the second element of this trio. So, for the above list, I need to recover the following result:

['ttyUSB1', 'ttyUSB4', 'ttyUSB7']

The code below works perfectly, but is not elegant, someone has some more inteigente solution?

def removeUselessSerialDoors(self, devices):

    new_list = []
    count = 0

    for port in devices:

        if count == 0:
            pass

        elif count == 1:
            new_list.append(port)

        elif count == 2:
            count = 0
            continue

        count = count + 1    

    return new_list

thanks for your time

Upvotes: 0

Views: 53

Answers (2)

Benjamin
Benjamin

Reputation: 2286

>>l=['ttyUSB0', 'ttyUSB1', 'ttyUSB2', 'ttyUSB3', 'ttyUSB4','ttyUSB5', 'ttyUSB6', 'ttyUSB7', 'ttyUSB8']
>>newList=[]
>>for i in range(1,len(l),3):
        newlist.append(l[i])
>>newList
   ['ttyUSB1', 'ttyUSB4', 'ttyUSB7']

enter image description here

Upvotes: 0

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

You can use slicing:

>>> l = ['ttyUSB0', 'ttyUSB1', 'ttyUSB2', 'ttyUSB3', 'ttyUSB4', 'ttyUSB5', 'ttyUSB6', 'ttyUSB7', 'ttyUSB8']
>>> l[1::3]
['ttyUSB1', 'ttyUSB4', 'ttyUSB7']

The 1 in [1::3] gives the index to start, and the 3 gives the 'multiplier':

>>> lst = range(1, 10)
>>> lst[::3]
[1, 4, 7]
>>> lst[1::3]
[2, 5, 8]
>>> lst[0::3]
[1, 4, 7]
>>> lst[0::2]
[1, 3, 5, 7, 9]
>>> lst[1::2]
[2, 4, 6, 8]
>>> 

Upvotes: 6

Related Questions