0

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?

user3447696
  • 167
  • 1
  • 1
  • 5

4 Answers4

1

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.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
0

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)

0
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 ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Wow, that's nasty and beautiful at the same time. I wonder whether it is "guaranteed" to work acress Python implementation, since in theory `izip` could fetch more than one item at a time and cache them. But I guess the CPython implementation is the reference here. – Niklas B. Apr 01 '14 at 21:09
-1

you can simply use slicing:

while l:
  a,l=l[:6],l[6:]
  doSomethingWith(a)
fredtantini
  • 15,966
  • 8
  • 49
  • 55