問題描述
我想通過一個(gè)迭代器反復(fù)(N 次)循環(huán)遍歷一個(gè)列表,以免在內(nèi)存中實(shí)際存儲(chǔ) N 個(gè)列表副本.有沒有一種內(nèi)置的或優(yōu)雅的方法可以在不編寫我自己的生成器的情況下做到這一點(diǎn)?
I'd like to cycle through a list repeatedly (N times) via an iterator, so as not to actually store N copies of the list in memory. Is there a built-in or elegant way to do this without writing my own generator?
理想情況下, itertools.cycle(my_list) 會(huì)有第二個(gè)參數(shù)來限制它循環(huán)的次數(shù)......唉,沒有這樣的運(yùn)氣.
Ideally, itertools.cycle(my_list) would have a second argument to limit how many times it cycles... alas, no such luck.
推薦答案
import itertools
itertools.chain.from_iterable(itertools.repeat([1, 2, 3], 5))
Itertools 是一個(gè)很棒的庫(kù).:)
Itertools is a wonderful library. :)
這篇關(guān)于有沒有一種優(yōu)雅的方法可以通過迭代循環(huán)遍歷列表 N 次(如 itertools.cycle 但限制循環(huán))?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!