首页 > 解决方案 > Looking for an elegant way for looping simultaneously over two list with different lengths

问题描述

I'm looking for the most elegant/short/pythonic way to iterate through two uneven lists simultaneously. If the shorter list ends at some point, it should start to iterate from the beginning.

So far, I managed to do it with the while, which I consider as ugly, and too long (from various reasons I need as short code as possible).

list1 = ["a", "b", "c"]
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

i1 = 0
i2 = 0
while True:
    if i2 == len(list2):
        break
    if i1 == len(list1):
        i1 = 0
    print(list1[i1], list2[i2])
    i1 += 1
    i2 += 1

The expected result should look like this. I'm achieving it with while loop (the code above). But I need to have as short code as possible:

a 1
b 2
c 3
a 4
b 5
c 6
a 7
b 8
c 9
a 10

标签: pythonpython-3.x

解决方案


zip both lists, feeding the shortest one to itertools.cycle so it repeats indefinitely (until list2 ends):

import itertools

list1 = ["a","b","c"]
list2 = [1,2,3,4,5,6,7,8,9,10]

for a,b in zip(itertools.cycle(list1),list2):
    print(a,b)

prints:

a 1
b 2
c 3
a 4
b 5
c 6
a 7
b 8
c 9
a 10

(of course don't use itertools.zip_longest as cycle never ends, which would create an infinite loop)


推荐阅读