简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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