gpt4 book ai didi

python - numpy数组eval表示公式

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:34 27 4
gpt4 key购买 nike

我想用 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])

关于python - numpy数组eval表示公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46662344/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com