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

后端 未结 6 1874
我寻月下人不归
我寻月下人不归 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:16

    As mentioned before, it works well with zip:

    Another example:

    from itertools import repeat
    
    fruits = ['apples', 'oranges', 'bananas']
    
    # Initialize inventory to zero for each fruit type.
    inventory = dict( zip(fruits, repeat(0)) )
    

    Result:

    {'apples': 0, 'oranges': 0, 'bananas': 0}
    

    To do this without repeat, I'd have to involve len(fruits).

提交回复
热议问题