简体   繁体   中英

Zip list with arrays to a dict doesn't produce correct results

I have this code:

import sympy
import numpy as np

arr = [np.array([ 1, 2,  3, 4]), np.array([ 5, 6, 7, 8])]
a,b = sympy.symbols('a b')
var = [a,b]

new_dict = dict(zip(str(var), arr))

And my output is:

print(new_dict)

{'[': array([1, 2, 3, 4]), 'a': array([5, 6, 7, 8])}

instead of:

{'a': array([1, 2, 3, 4]), 'b': array([5, 6, 7, 8])}

How can I fix that?

When you send a list to str() , it gives you the representation of that list as a string, which includes brackets and commas. You want the string representation of each value in that list:

new_dict = dict(zip(map(str, var), arr))

Or, better yet, since var seems to hold strings anyway:

new_dict = dict(zip(var, arr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM