2013-08-23 54 views
3

如果我有一個列表:遍歷列表以三個項目同時

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

我怎麼可以遍歷它,這樣我可以輸出如下:

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

哪裏' 「G」'? – TerryA

+1

「C」應輸出兩次? – falsetru

+0

@Haidro''G「'* over(ite)rated * .. – halirutan

回答

2

獲取的子列表[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

是,我記食譜p掛在身邊。

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

我喜歡這個迄今爲止最好的,但有什麼方法可以使用itertools函數嗎? –

+1

不是直接。這可能是itertools的一個很好的補充。 –

+0

@NoelEvans剛剛添加了一個:) – TerryA

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 
+0

看起來更像是「神奇」,而不是簡單地寫出來 –

+0

@Haidro尼斯。謝謝。 –

+0

問題是最後一項是'('G','','')'併產生'G' – newtover