如果我有一个列表:
["A","Bb","C","D","E","F","G"]
如何迭代它以便输出以下内容:
"A Bb C"
"D E F"
"G"
答案 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