简体   繁体   English

有没有一种pythonic方法可以一次遍历两个列表一个元素?

[英]Is there a pythonic way to iterate over two lists one element at a time?

I have two lists: [1, 2, 3] and [10, 20, 30].我有两个列表:[1, 2, 3] 和 [10, 20, 30]。 Is there a way to iterate moving one element in each list in each step?有没有办法在每一步中迭代移动每个列表中的一个元素? Ex (1, 10) (1, 20) (2, 20) (2, 30) (3, 30) I know zip moves one element in both lists in each step, but that's not what I'm looking for Ex (1, 10) (1, 20) (2, 20) (2, 30) (3, 30) 我知道 zip 在每个步骤中都会移动两个列表中的一个元素,但这不是我要找的

Is it what you expect:是否如您所愿:

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)]

For good measure, here's a solution that works with arbitrary iterables, not just indexable sequences:为了更好地衡量,这是一个适用于任意迭代的解决方案,而不仅仅是可索引序列:

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)]

One with zip and list comprehension.一个带有 zip 和列表理解的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM