如何将eval()函数与变量列表一起使用? [英] How to use eval() function with a list of variables?
问题描述
我有一个字符串函数列表:
I have a list of functions as strings:
["y + x + 3", "x**2 + y**2 - 17"] # 2 functions in list
我有一个 Sympy Symbol
对象(基本上是变量)的列表,它们的 .name
属性与函数字符串中的变量名称相对应:
I have a list of Sympy Symbol
objects (basically variables) whos .name
attribute cooresponds to the variables names in the function strings:
[Symbol(x), Symbol(y)]
# list element 0's .name attribute is "x"
我发现Python有一个名为 eval()
的简洁函数,可以评估字符串,例如:
I found that Python have a neat function called eval()
which can evaluate strings, for example:
x = 1
eval("x + 3") # Result should be 4
基本上,这就是我要对函数字符串进行的操作.但是,由于这是一个动态实现,因此我在程序中 eval()
上方的一行中没有定义变量,因此它们位于列表中.例如,在上面的示例中x被定义为1,因此 eval()
函数可以使用它.
Basically this is what I want to do with my functions strings. However, since this is a dynamic implementation I don't have variables defined on a line above eval()
in my program, they are in a list instead. For example, in the example above x is defined as 1, so then the eval()
function can use it.
但是我的变量在列表中,而不是在函数范围内定义为变量.如何使用 eval()
函数并利用变量列表?
But I have my variables in a list, not defined as a variable in the scope of my function. How could I use the eval()
function and utilize my list of variables?
推荐答案
eval
takes local variables as third argument(reference),
so you can do this:
from sympy import Symbol
zs = [Symbol('x'), Symbol('y')]
eval('x+y', None, dict([z.name, z] for z in zs))
但是,也许您应该使用SymPy的一部分 parse_expr .
However, maybe you should use parse_expr which is part of SymPy.
from sympy import Symbol
from sympy.parsing.sympy_parser import parse_expr
zs = [Symbol('x'), Symbol('y')]
parse_expr('x+y', local_dict=dict([z.name, z] for z in zs))
这篇关于如何将eval()函数与变量列表一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!