[英]How to iterate in pairs over a list with ODD cardinality in python
我想在 Python 中成對地迭代一個列表,除了該列表有奇數個元素。
我知道如果這個列表for item1,item2 in zip(alist[0::2],alist[1::2])
會起作用,但如果列表是奇數,循環會在處理最后一個項目之前中斷。
有什么有效的方法來處理這個問題嗎?
例子:
list a = (a,b,c,d,e,f,g)
Expected elements in each iteration:
(a,b)
(c,d)
(e,f)
(g,None) # or some other placeother value for the non-existent 2nd element of the pair
你可以 append None
:
for item1,item2 in zip(alist[0::2],alist[1::2]+[None]):
...
您可以使用itertools.zip_longest
:
from itertools import zip_longest
alist = ["a", "b", "c", "d", "e", "f", "g"]
for i in zip_longest(alist[0::2], alist[1::2]):
print(i)
印刷:
('a', 'b')
('c', 'd')
('e', 'f')
('g', None)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.