列表中的字符串,转换为函数 [英] String in list, into a function
本文介绍了列表中的字符串,转换为函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
myList = ['100', 'sin(x)', '0', '1']
我从文本文件中读取了这些字符串.现在,我想从该字符串执行函数 sin(x) -我希望这是任何函数表达式对该字符串的一般解释.
I read these strings from a text file. I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.
我尝试以下操作均未成功.
I have tried the following with no success.
myList[1].replace("'", "")
我想我要问的是如何从列表中提取字符串并使用它的原始文本".
I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.
最终目标是要获得此功能,其中myList [1]应该变为sin(x)
The end goal is to get this function, where myList[1] should turn to sin(x)
from math import sin
def f(x):
return myList[1]
因此,f(x)将给出此列表中sin(x)的计算值.
Thus f(x) will give the computed value of sin(x) from this list.
推荐答案
使用字典并将其存档
from math import sin
myList = ['100', 'sin(x)', '0', '1']
options = { 'sin(x)':sin }
options[myList[1]](1)
0.8414709848078965
这篇关于列表中的字符串,转换为函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文