gpt4 book ai didi

python - 随机执行一个函数

转载 作者:太空狗 更新时间:2023-10-30 00:27:58 25 4
gpt4 key购买 nike

考虑以下函数:

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

有没有办法选择一个函数随机运行?我尝试使用:

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

但它返回两个函数,我只希望它返回一个函数。

最佳答案

只调用selected 函数,而不是同时调用它们:

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()] 被创建时,你的旧代码调用了 both 函数,导致 Python 打印两个 ab。之后,它告诉 random.choice 从列表 [None, None]1 中选择,它什么也不做。您可以从下面的演示中看到这一点:

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

然而,新代码使用 random.choice 从列表 [a,b] 中随机选择一个函数对象:

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

然后它只调用该函数。


1函数默认返回None。由于 ab 缺少返回语句,因此它们都返回 None

关于python - 随机执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26640169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com