0

我有一个清单

L = [1, 2, 3, 4...]

其中有n*3元素。我希望能够做类似的事情

for a, b, c in three_tuple_split(L)

以pythonic的方式,但无法想出一个。

4

3 回答 3

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
于 2013-04-03T13:16:26.227 回答
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
于 2013-04-03T13:23:19.003 回答
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):
于 2013-04-03T13:24:14.383 回答