循环调用lambdify,避免显式调用 [英] call lambdify in a loop, avoid explicitly call

查看:80
本文介绍了循环调用lambdify,避免显式调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

var = ['a','b','c']
arr = np.array([ [1,2,3,4,5,6,7,8,9],
        [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
      ])

y = np.hsplit(arr,len(var))

newdict = {}
for idx,el in enumerate(y):
    newdict[str(var[idx])] = el

print(newdict)

我将数组拆分为3个新数组,每个数组对应var列表中的每个变量.

I am splitting the array in order to have 3 new arrays, one for each variable in the var list.

然后,我正在创建一个新的字典,以便为每个变量分配对应的数组.因此,我的结果是:

Then , I am creating a new dictionary in order to assign to every variable the corresponding array.So, my result now is:

{'a': array([[ 1. ,  2. ,  3. ],
       [ 0.1,  0.2,  0.3]]), 'b': array([[ 4. ,  5. ,  6. ],
       [ 0.4,  0.5,  0.6]]), 'c': array([[ 7. ,  8. ,  9. ],
       [ 0.7,  0.8,  0.9]])}

现在,我有一个表达式可以求值:

Now, I have an expression to evaluate:

expr = sympify('a + b +c')
f = lambdify(var, expr, 'numpy')

result = f(newdict['a'], newdict['b'], newdict['c'])

print(result)

因此,我正在使用lambdify,并且收到了正确的结果:

So , I am using lambdify and I am receiving the correct result:

[[ 12.   15.   18. ]
 [  1.2   1.5   1.8]]

我的问题是如何避免显式调用f(newdict['a'], newdict['b'], newdict['c'])?

My question is how to avoid calling explicitly f(newdict['a'], newdict['b'], newdict['c'])?

如何在循环中进行lambdify?

How can I have lambdify in a loop?

推荐答案

针对您特殊的交换函数(a + b + c):

For your particular commutative function (a + b + c):

f(*newdict.values())

对于非交换函数,需要指定键顺序(因为键在字典中是无序的),例如:

For non-commutative functions, it's required to specify key order (as keys are unordered in a dict), e.g.:

f(*[v for _, v in sorted(newdict.items())])

使用显式键:

f(*[newdict[k] for k in 'abc'])

使用OrderedDict:

from collections import OrderedDict
newdict = OrderedDict()
for idx,el in enumerate(y):
    newdict[str(var[idx])] = el

f(*newdict.values())

(f(*[1, 2, 3])等同于f(1, 2, 3).)

这篇关于循环调用lambdify,避免显式调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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