0

Suppose I have the following list:

['id-1213fsr53', 'WAITING', '54-81-24-40', 'world', 'id-343252sfsg', 'WAITING', '54-41-06-143', 'hello']

the list can be subdivided into tuples in the following format:

(id, status, ip-address, name)

So, in other to check the status, I need to iterate over that list by those 4 element tuples, like:

for s in status:
   (id, status, ip-address, name) = s # (s is a 4 element list)
   # increment s by 4, and continue the loop

How can I achieve such behavior in python?

cybertextron
  • 9,883
  • 26
  • 96
  • 199

3 Answers3

5

The easiest way is with the grouper itertools recipe:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You can use this like:

for s in grouper(status, 4):

Note that you will have issues if you use status for both unpacking one of the tuple values and for the raw data.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
1

Using a method of grouping elements into groups from the zip() docs:

data = ['id-1213fsr53', 'WAITING', '54-81-24-40', 'world', 'id-343252sfsg', 'WAITING', '54-41-06-143', 'hello']
for s in zip(*[iter(data)]*4):
    (id, status, ip_address, name) = s

You can also perform the unpacking in the iteration:

for id, status, ip_address, name in zip(*[iter(data)]*4):
    # do something

Here is what that zip() call is doing that allows for this type of iteration:

>>> zip(*[iter(data)]*4)
[('id-1213fsr53', 'WAITING', '54-81-24-40', 'world'), ('id-343252sfsg', 'WAITING', '54-41-06-143', 'hello')]
Andrew Clark
  • 192,132
  • 30
  • 260
  • 294
0

Try this:

for index in range(0, len(status), 4):
    (id,status,ip-address,name) = s[index:index+4]
merlin2011
  • 67,488
  • 40
  • 178
  • 299
  • @aruisdante it is not. – sashkello Mar 13 '14 at 23:52
  • Huh, you're right, I swear to god I just did this this morning and `list[0:99]` gave me the first 100 elements in the list, but apparently I'm crazy because I just did it in the terminal and it did not. – aruisdante Mar 13 '14 at 23:56