【问题标题】:How to iterate over two lists and recycle the second one until the first one is over如何迭代两个列表并回收第二个列表直到第一个列表结束
【发布时间】:2020-05-24 08:59:32
【问题描述】:

基本上我有这两个列表

listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
listtwo = ['1', '2', '3']

我想同步迭代这两个列表,只要最短的列表结束(在本例中为 listtwo),就会再次重新启动,直到 listone 完成。 示例:

a 1
b 2
c 3
d 1
e 2
f 3
j 1

像这样。

【问题讨论】:

    标签: python-3.x list loops


    【解决方案1】:

    附加到已接受的答案,

    如果列表长度未知。

    from itertools import cycle
    
    A = [1,2,3,4,5,6,7,8,9]
    B = ["A","B","C"]
    
    zip_list = list(zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B))
    
    for i, j in zip_list :
        print(i, j) 
    
    1 A
    2 B
    3 C
    4 A
    5 B
    6 C
    7 A
    8 B
    9 C
    
    [Program finished] 
    

    【讨论】:

      【解决方案2】:

      没有itertools.cycle() 或创建二级列表:

      listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
      listtwo = ['1', '2', '3']
      N = len(listtwo)
      
      for index, elem in enumerate(listone):
          elem2 = listtwo[index % N]
          print(elem, elem2)
      

      【讨论】:

        【解决方案3】:

        你可以使用itertools.cycle:

        from itertools import cycle
        
        for i, j in zip(listone, cycle(listtwo)):
            print(i, j)
        

        输出:

        a 1
        b 2
        c 3
        d 1
        e 2
        f 3
        j 1
        

        【讨论】:

          【解决方案4】:
          from math import ceil
          listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
          listtwo = ['1', '2', '3']
          listtwo_augmented = listtwo * ceil(len(listone)/len(listtwo))
          for e1, e2 in zip(listone, listtwo_augmented):
              print(e1, e2)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-11-27
            • 1970-01-01
            • 2019-10-18
            • 2020-04-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多