【发布时间】:2018-09-12 11:17:52
【问题描述】:
我正在尝试制作一个函数列表,我可以从中随机提取其中一个函数。我尝试了几种方法,既试图让它主动选择列表中的第二个函数,又试图让它随机。两者都失败了。
如果列表中包含文本而不是函数,则该列表可以正常工作。
q = [opt1(), opt2(), opt3()] 也激活了该功能,尽管我没有调用它们。
如何让它从列表中随机提取其中一个函数?
import random
def opt1():
print("hej1")
def opt2():
print("hej2")
def opt3():
print("hej3")
q = [opt1(), opt2(), opt3()]
health = "100"
p = "1"
print("you have ", p, " potions")
print("Your health is ", health,)
while True:
a = input("A =")
if a == "add":
health = int(health)
p = int(p) + 1
print("you have ", p, " potions")
print("Your health is ", health,)
a = input("A =")
if a == "fight":
q[1]
#random.choice(q)
【问题讨论】:
-
"尽管我没有调用它们,但仍激活函数" –
opt1()是函数调用。 -
只要在函数后面加上方括号,就可以调用该函数。因此,只需将函数名称放在列表中即可。
-
你为什么不给他们打电话?
-
将函数名称放入列表中,并在它们被选中时调用它们。
-
.. 并使用
q[1]()调用它 - 如果需要,您必须弄清楚如何为您的函数提供参数
标签: python python-3.x list function