Execute a function randomly

对着背影说爱祢 提交于 2020-04-12 20:28:22

问题


Consider the following functions:

def a():
    print "a"
def b():
    print "b"

Is there a way to pick a function to run randomly? I tried using:

random.choice([a(),b()])

but it returns both functions, I just want it to return one function.


回答1:


Only call the selected function, not both of them:

random.choice([a,b])()

Below is a demonstration:

>>> import random
>>> def a():
...     print "a"
...
>>> def b():
...     print "b"
...
>>> random.choice([a,b])()
a
>>> random.choice([a,b])()
b
>>>

Your old code called both functions when the list [a(),b()] was created, causing Python to print both a and b. Afterwards, it told random.choice to choose from the list [None, None]1, which does nothing. You can see this from the demonstration below:

>>> [a(),b()]
a
b
[None, None]
>>>

The new code however uses random.choice to randomly select a function object from the list [a,b]:

>>> random.choice([a,b])
<function b at 0x01AFD970>
>>> random.choice([a,b])
<function a at 0x01AFD930>
>>>

It then calls only that function.


1Functions return None by default. Since a and b lack return-statements, they each return None.




回答2:


Is it what you want?

random.choice([a,b])()



来源:https://stackoverflow.com/questions/26640169/execute-a-function-randomly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!