我想用 np 数组计算符号表达式
例子:
import numpy as np
a = np.array([1]*4)
b = np.array([2]*4)
res = repr(a) + ' + ' + repr(b)
value = eval(res)
错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'array' is not defined
我有一个解决方法,但我会知道我是否可以解决我最初的问题
在 stackoverflow 上找到解决方法 Python eval function with numpy arrays via string input with dictionaries
formula = 'x+y'
res = eval(formula,{'x':a, 'y':b})
编辑:
为了解决问题,在导入模块中添加数组定义
from numpy import array
请您参考如下方法:
表示形式为:array([1, 1, 1, 1])。所以我们需要导入一个 array 定义。所以以下应该有效:
from numpy import array
a = array([1] * 4)
b = array([2] * 4)
res = repr(a) + ' + ' + repr(b)
eval(res)
结果:
array([3, 3, 3, 3])
