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
  • 10,547
  • 28
  • 104
  • 208

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
  • 115,751
  • 26
  • 228
  • 437
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
  • 202,379
  • 35
  • 273
  • 306
0

Try this:

for index in range(0, len(status), 4):
    (id,status,ip-address,name) = s[index:index+4]
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • @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