Question

I have a list of 480 tuples.

list = [(7,4), (6, 1), (4, 8)....]

I need to take the first six tuples and put them in a temporary variable to perform some assessment of them. THEN I need to take the following six tuples and put them in the temporary variable and do the same assessment, and then the next six tuples and so on.

I am not sure how to set this up in a loop--how to grab six tuples and then take the next six tuples from the list? Or is there an easier way to set up the data structure of tuples to do this?

Was it helpful?

Solution 2

from itertools import izip_longest
groups_of_six = izip_longest(*[iter(my_list_of_tuples)]*6)
for a_group in groups_of_six:
    do_some_processing_on(a_group)

thats my favorite way to do this :P

and since its a generator you are not looping over and over ...

OTHER TIPS

This returns a list of lists, with each sublist consisting of six tuples:

[my_list[i:i+6] for i in range(0, len(my_list), 6)]

Note that if you are using Python 2 you should use xrange instead of range so you don't have to iterate continuously.

You could think about using a for loop to take care of it.

myList = [(7,4), (6, 1), (4, 8), (4, 9), (3, 4), (9, 2), (7, 3)]
newList = []
for x in xrange(len(myList)):
    if x % 6 == 0:
        newList.append(myList[x])

print newList

There are shorter ways to do this, but I think mine is fairly readable and neat. You could also replace the newList.append line with anything you need (for example some sort of function)

you can simply use slicing:

while l:
  a,l=l[:6],l[6:]
  doSomethingWith(a)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top