Is there an elegant way to cycle through a list N times via iteration (like itertools.cycle but limit the cycles)?

前端 未结 6 717
执念已碎
执念已碎 2020-12-09 05:56

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

6条回答
  •  死守一世寂寞
    2020-12-09 06:23

    All the other answers are excellent. Another solution would be to use islice. This allows you to interrupt the cycle at any point:

    >>> from itertools import islice, cycle
    >>> l = [1, 2, 3]
    >>> list(islice(cycle(l), len(l) * 3))
    [1, 2, 3, 1, 2, 3, 1, 2, 3]
    >>> list(islice(cycle(l), 7))
    [1, 2, 3, 1, 2, 3, 1]
    

提交回复
热议问题