在循环中调用lambdify,显式避免

2024-09-27 22:09:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

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列表中的每个变量。你知道吗

然后,我创建一个新字典,以便为每个变量分配相应的数组。所以呢,我现在的结果是:

{'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]])}

现在,我要计算一个表达式:

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

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

print(result)

因此,我使用lambdify并得到正确的结果:

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

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

我怎么能让lambdify在一个循环中呢?你知道吗


Tags: 密码lenvarnp数组resultarrayel
1条回答
网友
1楼 · 发布于 2024-09-27 22:09:16

对于特定的交换函数(a + b + c):

f(*newdict.values())

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

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)。)

相关问题 更多 >

    热门问题