简体   繁体   中英

How to change string elements in a list from strings to numpy array names?

I have a python list, like so:

list = [('array_1','array_2'),('array_1','array_3'),('array_2','array_3')]

The pairs in the list above are actually named numpy arrays, so I want to remove the quotes around each array name so that I'm left with:

list = [(array_1, array_2), (array_1, array_3), (array_2, array_3)]

How do I go about doing this?

This will output the numpy array (like array_1 ):

# str will be like : 'array_1' 
globals()[str]

or

eval(str)

Note:

But I recommend to create a dictionary with keys as the strings and values as the corresponding arrays instead of eval and globals()

like this:

dict_ = {'array_1': array_1, 'array_2': array_2, 'array_3': array_3} 

And use this dictionary wherever you want to access the variable

Now you lst will contain actual NumPy arrays instead of just strings.

lst = [("array_1", "array_2"), ("array_1", "array_3"), ("array_2", "array_3")]

lst = [(globals()[i], globals()[j]) for i, j in lst]

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