带有 numpy 数组的 Python eval 函数通过带有字典的字符串输入 [英] Python eval function with numpy arrays via string input with dictionaries

查看:84
本文介绍了带有 numpy 数组的 Python eval 函数通过带有字典的字符串输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中实现代码,其中变量存储在 numpy 向量中.我需要执行简单的操作:类似于 (vec1+vec2^2)/vec3.每个向量的每个元素都被求和并相乘.(MATLAB elementwise .* 操作的模拟).

I am implementing the code in python which has the variables stored in numpy vectors. I need to perform simple operation: something like (vec1+vec2^2)/vec3. Each element of each vector is summed and multiplied. (analog of MATLAB elementwise .* operation).

问题在于我的代码中有存储所有向量的字典:

The problem is in my code that I have dictionary which stores all vectors:

    var = {'a':np.array([1,2,2]),'b':np.array([2,1,3]),'c':np.array([3])}

第三个向量只是 1 个数字,这意味着我想将此数字乘以其他数组中的每个元素,例如 3*[1,2,3].同时我有作为字符串提供的公式:

The 3rd vector is just 1 number which means that I want to multiply this number by each element in other arrays like 3*[1,2,3]. And at the same time I have formula which is provided as a string:

    formula = '2*a*(b/c)**2'

我正在使用正则表达式替换公式:

I am replacing the formula using Regexp:

    formula_for_dict_variables = re.sub(r'([A-z][A-z0-9]*)', r'%(\1)s', formula)

产生结果:

    2*%(a)s*(%(b)s/%(c)s)**2

并替换字典变量:

    eval(formula%var)

在这种情况下,我只有纯数字(不是 numpy 数组),一切正常,但是当我将 numpy.arrays 放入 dict 时,我收到一个错误.

In the case then I have just pure numbers (Not numpy arrays) everything is working, but when I place numpy.arrays in dict I receive an error.

  1. 你能举个例子我如何解决这个问题,或者建议一些不同的方法.鉴于向量存储在字典中,公式是一个字符串输入.

  1. Could you give an example how can I solve this problem or maybe suggest some different approach. Given that vectors are stored in dictionary and formula is a string input.

我还可以将变量存储在任何其他容器中.问题是我在执行代码之前不知道变量和公式的名称(它们由用户提供).

I also can store variables in any other container. The problem is that I don't know the name of variables and formula before the execution of code (they are provided by user).

另外,我认为遍历向量中每个元素的迭代可能会很慢,因为 python for 循环很慢.

Also I think iteration through each element in vectors probably will be slow given the python for loops are slow.

推荐答案

使用 numexpr,那么你可以这样做:>

Using numexpr, then you could do this:

In [143]: import numexpr as ne
In [146]: ne.evaluate('2*a*(b/c)**2', local_dict=var)
Out[146]: array([ 0.88888889,  0.44444444,  4.        ])

这篇关于带有 numpy 数组的 Python eval 函数通过带有字典的字符串输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆