问题
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