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

后端 未结 9 1842
借酒劲吻你
借酒劲吻你 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:41

    Here is an approach that doesn't require the use of a for loop or defining an intermediate function or lambda function (and is also a one-liner). The method combines the following two ideas:

    • calling the iter() built-in function with the optional sentinel argument, and

    • using the itertools recipe for advancing an iterator n steps (see the recipe for consume()).

    Putting these together, we get:

    next(islice(iter(do, object()), 3, 3), None)
    

    (The idea to pass object() as the sentinel comes from this accepted Stack Overflow answer.)

    And here is what this looks like from the interactive prompt:

    >>> def do():
    ...   print("called")
    ... 
    >>> next(itertools.islice(iter(do, object()), 3, 3), None)
    called
    called
    called
    

提交回复
热议问题