随机执行功能 [英] Execute a function randomly
问题描述
请考虑以下功能:
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.
推荐答案
仅调用 selected 函数,而不是同时调用它们:
Only call the selected function, not both of them:
random.choice([a,b])()
下面是一个演示:
>>> import random
>>> def a():
... print "a"
...
>>> def b():
... print "b"
...
>>> random.choice([a,b])()
a
>>> random.choice([a,b])()
b
>>>
创建列表[a(),b()]
时,旧代码都称为 起作用,导致Python同时打印a
和b
.之后,它告诉random.choice
从列表[None, None]
1 中进行选择,该列表什么也不做.您可以从下面的演示中看到这一点:
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]
>>>
但是,新代码使用random.choice
从列表[a,b]
中随机选择一个功能对象:
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>
>>>
然后仅调用该函数.
1 默认情况下,函数返回None
.由于a
和b
缺少返回语句,因此它们每个都返回None
.
1Functions return None
by default. Since a
and b
lack return-statements, they each return None
.
这篇关于随机执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!