我正在迭代一个列表,并希望使用该列表项来调用函数.这就是我try 过的:

def get_list1():
    ....do something
def get_list2():
    ....do something
def get_list3():
    ....do something

data = ['list1', 'list2', 'list3']

for list_item in data:
    function_call = 'get_' + list_item
    function_call()

但我收到错误"TypeError:‘Str’Object Is Not Callable" 我还有其他几种方法可以攻击它,但了解这一点对future 也是有帮助的.谢谢!

推荐答案

只是给出一个使用词典的例子(就像在其他答案中提到的那样),如果你觉得有用的话.

def get_list1():
    print('get_list1 executes')


def get_list2():
    print('get_list2 executes')


# Create a dictionary with a reference to your functions as values
# (note no parenthesis, as that would execute the function here instead)
fns = {
    'example_key1': get_list1,
    'example_key2': get_list2,
}

print(type(fns['example_key1']))  # returns <class 'function'>

# If you still want a list
lst = list(fns)  # Create a list containing the keys of the fns dictionary
for fn in lst:
    # Iterate through the list (of keys) and execute the function
    # found in the value.
    fns[fn]()

# Or you can now just simply iterate through the dictionary instead, if you wish:
for fn in fns.values():
    fn()

此代码生成:

<class 'function'>
get_list1 executes
get_list2 executes
get_list1 executes
get_list2 executes

Python-3.x相关问答推荐

根据收件箱内部的值以行降序的特定顺序重新排序列

使用魔方无法从图像中识别单个字符

只有在Chrome尚未打开的情况下,打开Chrome后,PySimpleGUI窗口才会崩溃

是否可以使用参数对Flask重定向?

Pandas -我们如何在一行中应用多个要求

Heroku 中的未知错误代码缺少一个或多个参数

在新数据帧上自动提取两个字符串 python 之间的相等性

如何对具有多个列值的 pandas 数据框进行数据透视/数据透视表

python2和python3中的列表生成器

Einsum 对于张量乘法很慢

使用 RANSAC 在激光雷达点云中查找电力线

将元组列表转换为以整个元组为键的字典列表

正则表达式来识别用 Python 写成单词的数字?

Python 3 `str.__getitem__` 的计算复杂度是多少?

FastAPI - 调用 API 时设置 response_model_exclude

为什么Pandas会在 NaN 上合并?

cv2 python 没有 imread 成员

使用 python2 和 python3 创建一个 virtualenv

matplotlib - 模块sip没有属性setapi

如何修复:cx_Oracle.DatabaseError:DPI-1047:找不到 64 位 Oracle 客户端库 - Python