多次迭代列表

问题描述 投票:0回答:4

我想多次迭代列表。例如:

mylist = [10,2,58]

for i in iterate_multiple_times(mylist, 3):
    print(i)

应打印:

10
2
58
10
2
58
10
2
58

列表很长,我不想为了缩进/样式目的创建嵌套的

for
循环。

是否有比以下更好的解决方案(例如从辅助存储的角度)?

from itertools import chain, repeat

for i in chain.from_iterable(repeat(mylist, 3)):
    print(i)
python loops iteration
4个回答
4
投票

您可以在生成器表达式中使用嵌套的

for
循环:

>>> mylist = [10, 2, 58]
>>> for i in (x for _ in range(3) for x in mylist):
...     print(i)

0
投票

我的列表 = [10, 2, 58]

x3_我的列表 = 我的列表 * 3


-1
投票

不,你拥有的已经是最好的了。

repeat
chain.from_iterable
都是懒惰的,您没有创建整个列表的副本。您可能想将其提取到 如果多次使用,则为单独的功能

参见Itertools食谱

def ncycles(iterable, n):
    "Returns the sequence elements n times"
    from itertools import chain, repeat
    return chain.from_iterable(repeat(iterable, n)) 
    # the general recipe wraps iterable in tuple()
    # to ensure you can walk it multiple times
    # here we know it is always a list

mylist = [10,2,58]

for i in ncycles(mylist, 3):
    print(i)

-3
投票

除了使用

itertools
原语之外,您还可以乘以列表:

for i in mylist * 3: print(i)

或者创建您自己的程序:

def mul(iterable, amount):
   while amount > 0:
      for x in iterable: yield x
      amount -= 1

恐怕标准库/内置函数不多。

© www.soinside.com 2019 - 2024. All rights reserved.