[英]Iterate through a List Multiple times Cyclically starting from the Matching Index
[英]Iterate through a list multiple times
我想遍歷一個列表多次。 例如:
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)
您可以在生成器表達式中使用嵌套的for
循環:
>>> mylist = [10, 2, 58]
>>> for i in (x for _ in range(3) for x in mylist):
... print(i)
不,您所擁有的一切都差不多。 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)
除了使用itertools
原語以外,您還可以將列表相乘:
for i in mylist * 3: print(i)
或創建自己的過程:
def mul(iterable, amount):
while amount > 0:
for x in iterable: yield x
amount -= 1
恐怕標准庫/內置庫中沒有太多內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.