How do I call a function twice or more times conse

2019-03-09 18:00发布

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

do()
do()
do()

maybe like :

3*do()

8条回答
贪生不怕死
2楼-- · 2019-03-09 18:23

My two cents:

from itertools import repeat 

list(repeat(f(), x))  # for pure f
[f() for f in repeat(f, x)]  # for impure f
查看更多
我想做一个坏孩纸
3楼-- · 2019-03-09 18:30

Three more ways of doing so:

(I) I think using map may also be an option, though is requires generation of an additional list with Nones in some cases and always needs a list of arguments:

def do():
    print 'hello world'

l=map(lambda x: do(), range(10))

(II) itertools contain functions which can be used used to iterate through other functions as well https://docs.python.org/2/library/itertools.html

(III) Using lists of functions was not mentioned so far I think (and it is actually the closest in syntax to the one originally discussed) :

it=[do]*10
[f() for f in it]

Or as a one liner:

[f() for f in [do]*10]
查看更多
登录 后发表回答