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

前端 未结 6 714
执念已碎
执念已碎 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:28

    @Darthfett's answer is documented as an itertools recipes:

    from itertools import chain, repeat
    
    def ncycles(iterable, n):
        "Returns the sequence elements n times"
        return chain.from_iterable(repeat(tuple(iterable), n))
    
    
    list(ncycles(["a", "b"], 3))
    # ['a', 'b', 'a', 'b', 'a', 'b']
    

    For convenience, I add that the more_itertools library implements this recipe (and many others) for you:

    import more_itertools as mit
    
    list(mit.ncycles(["a", "b"], 3))
    # ['a', 'b', 'a', 'b', 'a', 'b']
    

提交回复
热议问题