How do I call a function twice or more times consecutively?

后端 未结 9 1827
借酒劲吻你
借酒劲吻你 2020-12-05 00:02

Is there a short way to call a function twice or more consecutively in Python? For example:

do()
do()
do()

maybe like:

3*do         


        
9条回答
  •  醉梦人生
    2020-12-05 00:36

    You can use itertools.repeat with operator.methodcaller to call the __call__ method of the function N times. Here is an example of a generator function doing it:

    from itertools import repeat
    from operator import methodcaller
    
    
    def call_n_times(function, n):
        yield from map(methodcaller('__call__'), repeat(function, n))
    

    Example of usage:

    import random
    from functools import partial
    
    throw_dice = partial(random.randint, 1, 6)
    result = call_n_times(throw_dice, 10)
    print(list(result))
    # [6, 3, 1, 2, 4, 6, 4, 1, 4, 6]
    

提交回复
热议问题