迭代列表一次取三个项目

时间:2013-08-23 09:39:43

标签: python

如果我有一个列表:

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

如何迭代它以便输出以下内容:

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

3 个答案:

答案 0 :(得分:4)

是我一直闲逛的食谱。

def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

答案 1 :(得分: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']

答案 2 :(得分: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