从随机Python模块获取输出



我正在尝试运行一个脚本,该脚本接受列表中的五个函数,并使用random模块随机选择一个。

myList = [quote1(), quote2(), quote3(), quote4(), quote5()]
def random_output(): random.choice(myList)
print(random_output) 

然而,在运行时,它只是同时打印所有引号,然后是<function random_output at 0x0000019F66EF4430>

您应该将函数放在myList中,而不是它们调用的结果。然后用random.choice:选择后调用函数

myList = [quote1, quote2, quote3, quote4, quote5]
def random_output():
# select a random function
# call it, and return its output
return random.choice(myList)()
print(random_output())

您不需要只调用另一个函数B的函数a。只需调用函数B:

import random
myList = [quote1(), quote2(), quote3(), quote4(), quote5()]
random.choice(myList)

如果真的想把它放在一个函数中,也许是因为你在那里做其他事情,你应该总是传递你的函数需要的东西,并返回它产生的东西(这被称为"纯"函数(:

def random_output(aList):
return random.choice(aList)

然后称之为:

random_output(myList)

如果你还不想调用函数quote1quote2等,那么在你想调用它们之前,你不应该在它们后面放括号。例如:

funcs = [quote1, quote2, quote3, quote4, quote5]
random_func = random.choice(funcs)
result = random_func(my_input)

最新更新