我有一个清单
L = [1, 2, 3, 4...]
有n*3
个元素。我希望能够做类似
for a, b, c in three_tuple_split(L)
以pythonic的方式,但不能拿出一个。
答案 0 :(得分:3)
低效但是pythonic解决方案:
for a, b, c in zip(*[iter(seq)]*3): pass
要实现更高效的实施,请查看itertools
grouper食谱:
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
答案 1 :(得分:0)
#!/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
答案 2 :(得分:0)
只需使用切片和for循环。
def break_into_chunks(l,n):
x = len(l)
step = x//n
return [l[i:i+step] for i in range(0,x,step)]
或者慢一点:
def break_into_chunks(l,n):
return [l[i:i+len(l)//n] for i in range(0,len(l),len(l)//n)]
使用:
for a, b, c in break_into_chunks(L,3):