What is the purpose in Python's itertools.repeat?

后端 未结 6 1887
我寻月下人不归
我寻月下人不归 2020-12-01 02:02

Every use I can think of for Python\'s itertools.repeat() class, I can think of another equally (possibly more) acceptable solution to achieve the same effect. For example:<

6条回答
  •  心在旅途
    2020-12-01 02:22

    I usually use repeat in conjunction with chain and cycle. Here is an example:

    from itertools import chain,repeat,cycle
    
    fruits = ['apples', 'oranges', 'bananas', 'pineapples','grapes',"berries"]
    
    inventory = list(zip(fruits, chain(repeat(10,2),cycle(range(1,3)))))
    
    print inventory
    

    Puts the first 2 fruits as value 10, then it cycles the values 1 and 2 for the remaining fruits.

提交回复
热议问题