3

如果我有一个清单:

["A","Bb","C","D","E","F","G"]

我怎样才能迭代它,以便我可以输出以下内容:

"A Bb C"
"D E F"
"G"
4

3 回答 3

4

是我一直在闲逛的食谱。

def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
于 2013-08-23T09:45:32.480 回答
3

你可以itertools.izip_longest在这里使用:

>>> from itertools import izip_longest
>>> L = ["A","Bb","C","D","E","F","G"]
>>> for item in izip_longest(*[iter(L)]*3, fillvalue=''):
...     print ' '.join(item)
... 
A Bb C
D E F
G  
于 2013-08-23T09:47:08.013 回答
3

获取[0:3], [3:6], [6:9], ...的子列表

>>> xs = ["A","Bb","C","D","E","F","G"]
>>> [' '.join(xs[i:i+3]) for i in range(0, len(xs), 3)]
['A Bb C', 'D E F', 'G']
于 2013-08-23T09:43:46.277 回答