Python列表迭代比其他列表

我有2个清单

lst1 = [1,2,3,4,5,6,7,8,9,10]
lst2 = ['a','b','c','d']

我想输出为

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

如何在python中实现?

评论
  • 灭世
    灭世 回复

    Use zip and itertools.cycle:

    from itertools import cycle
    
    lst1 = [1,2,3,4,5,6,7,8,9,10]
    lst2 = ['a','b','c','d']
    
    for x, y in zip(lst1, cycle(lst2)):
        print(f"{x} - {y}")
    

    输出:

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

  • punde
    punde 回复

    如果lst1始终大于lst2,这将很容易

    lst1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    lst2 = ['a', 'b', 'c', 'd']
    
    for i in range(len(lst1)):
        j = i % len(lst2)
        print(lst1[i],' - ',lst2[j])