【问题标题】:How do I iterate between lists of different lenghts?如何在不同长度的列表之间进行迭代?
【发布时间】:2020-10-06 13:22:06
【问题描述】:

我有两个列表需要一起迭代。让我展示一下:

listA=[1,2,3,4]
listB=["A","B","C"]

从这些列表中我想要这个列表

ListC=("1A","2B","3C","4A")

甚至可以创建一个更长的列表,我可以在其中循环相同的迭代

ListC=("1A","2B","3C","4A","1B","2C","3A","4C".... and so on)

我在网上找不到任何可以回答这个问题的教程 谢谢。

【问题讨论】:

  • 您希望您的ListC 存在多长时间?什么是结束/最后一个元素标准?

标签: python list loops iteration


【解决方案1】:

使用zipitertools.cycle

>>> from itertools import cycle
>>> listA = [1, 2, 3, 4]
>>> listB = ["A", "B", "C"]
>>> [f'{x}{y}' for x, y in zip(listA, cycle(listB))]
['1A', '2B', '3C', '4A']

# listA:         1    2    3    4
# cycle(listB): "A"  "B"  "C"  "A"  "B"  "C" ...

cycle 无休止地循环遍历其论点的元素; zip 在其较短的参数用完后停止迭代。

您可以将cycle两个 列表一起使用,但结果将是一个无限的值序列;您需要使用 itertools.islice 之类的东西来获取结果的有限前缀。

>>> from itertools import cycle, islice
>>> [f'{x}{y}' for x, y in islice(zip(cycle(listA), cycle(listB)), 8)]
['1A', '2B', '3C', '4A', '1B', '2C', '3A', '4B']

# cycle(listA):  1   2   3   4   1   2   3   4   1   2   3   4   1  ...
# cycle(listB): "A" "B" "C" "A" "B" "C" "A" "B" "C" "A" "B" "C" "A" ...
# Note that the result itself is a cycle of 12 unique elements, because
# the least common multiple (LCM) of 3 and 4 is 12.

【讨论】:

    【解决方案2】:
    listA=[1,2,3,4]
    listB=["A","B","C"]
    listC=[]
    
    for a in listA:
        index = listA.index(a)
        if listA.index(a) > len(listB) - 1:
            if listC[-1][1] != listB[-1]:
                index = listB.index(listC[-1][1]) + 1
            else:
                index = 0
        listC.append(str(a)+listB[index])
    
    print(listC)
    
    

    【讨论】:

    • 除了繁琐之外,这假设列表没有任何重复; index 仅返回项目第一次出现的索引。
    • 如果listA 的元素不是唯一的,那不是一个好主意,因为list.index 返回元素的第一次出现
    【解决方案3】:

    您可以使用模数来处理此类问题。这是重复 100 次的代码:

    l1 = [1, 2, 3, 4]
    l2 = ['a', 'b', 'c']
    
    result = []
    for i in range(100):
        result.append(str(l1[i % len(l1)]) + l2[i % len(l2)])
    
    print (result)
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2018-02-02
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多