I have a list
L = [1, 2, 3, 4...]
which have n*3
elements. I want to be able to do something like
for a, b, c in three_tuple_split(L)
in a pythonic way but can't come up with one.
I have a list
L = [1, 2, 3, 4...]
which have n*3
elements. I want to be able to do something like
for a, b, c in three_tuple_split(L)
in a pythonic way but can't come up with one.
Inefficient but pythonic solution:
for a, b, c in zip(*[iter(seq)]*3): pass
For a more efficient implementation, look at the itertools
grouper recipe:
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
for a, b, c in grouper(3, seq):
pass
#!/usr/bin/env python
mylist = range(21)
def three_tuple_split(l):
if len(l)%3 != 0:
raise Exception('bad len')
for i in xrange(0,len(l),3):
yield l[i:i+3]
for a,b,c in three_tuple_split(mylist):
print a,b,c
Just use slices and a for loop.
def break_into_chunks(l,n):
x = len(l)
step = x//n
return [l[i:i+step] for i in range(0,x,step)]
Or a slower one:
def break_into_chunks(l,n):
return [l[i:i+len(l)//n] for i in range(0,len(l),len(l)//n)]
To use:
for a, b, c in break_into_chunks(L,3):