gpt4 book ai didi

python - 如何从列表中调用函数?

转载 作者:行者123 更新时间:2023-11-28 19:55:09 25 4
gpt4 key购买 nike

例如,我有以下列表:

method = [fun1, fun2, fun3, fun4]

然后我显示一个菜单,用户必须在其中选择 1-4 中的一个数字 (len(method))。如果用户选择i,我必须使用函数funi。我该怎么做?

例如。

A=['hello','bye','goodbye']
def hello(n):
print n**2
def bye(n):
print n**3
def goodbye(n):
print n**4

如果我想通过数组 A 调用函数 bye,使用

>>>A[1](7)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
A[2](5)
TypeError: 'str' object is not callable

如何使用保存在 A 中的名称来调用我的函数?因为每个方法都保存在一个字符串中。

最佳答案

让我们看看...

您可以像 fn() 那样使用括号 () 调用函数 fn

您可以通过索引运算符 [] 访问列表中的项目,如 lst[idx]

因此,通过结合两个 lst[idx](*args)

编辑

Python 列表索引从零开始,因此第一项为 0,第二项为 1,依此类推...如果用户选择 1-4,则必须减去一个。

编辑

鉴于澄清,可以做以下事情

def method1():
pass

def method2():
pass


methods = [method1, method2]

您可以使用上面的逻辑。这样,您就不必将函数名称的字符串实际解析为实际函数。

请记住,python 中的函数是一流的,因此您可以将它们的引用存储到列表中(我们在 methods=[] 行中所做的)

关于python - 如何从列表中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562723/

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