![](/img/trans.png)
[英]Is there a pythonic way to iterate through the difference of two lists?
[英]Is there a pythonic way to iterate over two lists one element at a time?
我有兩個列表:[1, 2, 3] 和 [10, 20, 30]。 有沒有辦法在每一步中迭代移動每個列表中的一個元素? Ex (1, 10) (1, 20) (2, 20) (2, 30) (3, 30) 我知道 zip 在每個步驟中都會移動兩個列表中的一個元素,但這不是我要找的
是否如您所願:
def zip2(l1, l2):
for i, a in enumerate(l1):
for b in l2[i:i+2]:
yield (a, b)
>>> list(zip2(l1, l2))
[(1, 10), (1, 20), (2, 20), (2, 30), (3, 30)]
為了更好地衡量,這是一個適用於任意迭代的解決方案,而不僅僅是可索引序列:
def frobnicate(a, b):
ita, itb = iter(a), iter(b)
flip = False
EMPTY = object()
try:
x, y = next(ita), next(itb)
yield x, y
except StopIteration:
return
while True:
flip = not flip
if flip:
current = y = next(itb, EMPTY)
else:
current = x = next(ita, EMPTY)
if current is EMPTY:
return
yield x, y
def dupe(l):
return [val for val in l for _ in (0,1)]
list(zip(dupe([1,2,3]), dupe([10,20,30])[1:]))
# [(1, 10), (1, 20), (2, 20), (2, 30), (3, 30)]
一個帶有 zip 和列表理解的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.