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

时间:2021-07-26 16:27:57

标签: python python-3.x

我有两个列表:[1, 2, 3] 和 [10, 20, 30]。有没有办法在每一步中迭代移动每个列表中的一个元素?前任 (1, 10) (1, 20) (2, 20) (2, 30) (3, 30) 我知道 zip 会在每一步中移动两个列表中的一个元素,但这不是我要找的

3 个答案:

答案 0 :(得分:4)

是否如您所愿:

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

答案 1 :(得分:1)

为了更好的衡量,这里有一个适用于任意迭代的解决方案,而不仅仅是可索引的序列:

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

答案 2 :(得分:1)

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 和列表解析的一个。