【发布时间】:2021-12-01 19:33:12
【问题描述】:
我已经从电子邮件中抓取了一些字符串到一个列表中。这些字符串对应于我希望稍后能够调用的函数的名称。我不能以它们当前的形式调用它们,所以有没有办法将字符串列表转换为我可以调用的函数列表?
例如:
a = ['SU', 'BT', 'PL']
str = 'sdf sghf sdfgdf SU agffg BL asu'
matches = [x for x in a if x in str]
print(matches)
返回:
['SU', 'BL']
但是给定格式,我不能从这个列表中调用函数 SU 和 BL。
【问题讨论】:
-
你可以制作一个函数字典,其中字符串是键,函数是值。然后运行
your_dict[key]()。你试过了吗? -
Python 中的函数名本身就是一个变量。所以你真正想做的是从它的名字中检索一个变量引用。方法是运行
import sys然后getattr(sys.modules[__name__], FUNCTION_NAME)。它将从全局范围内为您检索变量。例如,如果您已经定义了一个名为myfunc的函数,那么您可以使用f = getattr(sys.modules[__name__], 'myfunc')。然后你可以从你的变量中调用函数:f()。它将调用函数myfunc()。 -
一个建议 - 不要使用
str作为变量。谢谢 -
@Mahrkeenerh 非常正确。
>>> str(4) ; '4' ; >>> str = 'blalsd' ; >>> str(4) ; Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object is not callable -
巧合的是,这个例子说明了函数名称与 Python 中的其他变量的区别
标签: python