Reputation: 5691
I have this code:
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)
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)
So , I am using lambdify and I am receiving the correct result:
[[ 12. 15. 18. ]
[ 1.2 1.5 1.8]]
My question is how to avoid calling explicitly f(newdict['a'], newdict['b'], newdict['c'])
?
How can I have lambdify in a loop?
Upvotes: 3
Views: 202
Reputation: 3836
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())])
With explicit keys:
f(*[newdict[k] for k in 'abc'])
Using 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])
is equivalent to f(1, 2, 3)
.)
Upvotes: 4