Cod*_*lus 2 python evaluation functional-programming symbols
在Python中,我试图弄清楚如何评估在程序中作为字符串给出的命令.例如,考虑内置的数学函数sin,cos和tan
假设我将这些功能作为列表给出;
li = ['sin', 'cos', 'tan']
Run Code Online (Sandbox Code Playgroud)
现在,我想迭代列表中的每个元素并将每个函数应用于数字参数:
x = 45
for func in li:
func(x)
Run Code Online (Sandbox Code Playgroud)
上面显然不会起作用,因为func是一个字符串,只是显示了这个想法.在lisp中,我可以使每个函数成为带引号的符号,然后与上面的内容进行类似的评估(当然,在lisp语法中,但是这个想法是相同的).
这是如何在python中完成的?
谢谢,如果您需要更多信息,请告诉我们!
只需使用这些功能:
from math import sin, cos, tan
li = [sin, cos, tan]
Run Code Online (Sandbox Code Playgroud)
如果你真的需要使用字符串,请创建一个字典:
funcs = {'sin': sin, 'cos': cos, 'tan': tan}
func = funcs[string]
func(x)
Run Code Online (Sandbox Code Playgroud)
这里有几个选项,我列出了以下一些更好的选项:
如果所有功能都来自同一模块,则可以使用module.getattr(func)该功能访问该功能.在这种情况下,sin,cos和tan都是数学函数,因此您可以执行以下操作:
import math
li = ['sin', 'cos', 'tan']
x = 45
for func in li:
x = getattr(math, func)(x)
Run Code Online (Sandbox Code Playgroud)创建将名称映射到函数的字典,并将其用作查找表:
import math
table = {'sin': math.sin, 'cos': math.cos, 'tan': math.tan}
li = ['sin', 'cos', 'tan']
x = 45
for func in li:
x = table[func](x)
Run Code Online (Sandbox Code Playgroud)将函数直接放在列表中:
import math
li = [math.sin, math.cos, math.tan]
x = 45
for func in li:
x = func(x)
Run Code Online (Sandbox Code Playgroud)