I have a list including some names, as example:
data_set_names=['matrix_1','matrix_2','matrix_3']
.
Inside a loop, I want to use each of these names for storing the output of some computations, which are as NumPy array. I highly appreciate if someone could tell me how to do that. As I looked it up online, exec()
function can be used to convert a string to a variable name, but in my case, it is not useful.
Asked
Active
Viewed 524 times
0

Shahin
- 5
- 1
-
Would storing the matrices as values in a dictionary where the keys are the strings in the list work for you? – ChrisOram Jul 30 '21 at 10:34
-
Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Matthias Jul 30 '21 at 11:17
2 Answers
0
You could think about using globals()
or locals()
depending on your needs. Both are a dictionary of the variables you are using in your code, (global or locals) and from there you can assign a variable as a string, in your case something like:
for i in data_set_names:
globals()[i] = 'your data here'

PiElLi
- 18
- 6
-
So why not use an explicit dictionary rather than doing this weird stuff? – Matthias Jul 30 '21 at 11:15
-
Thank you for your suggestion. Indeed, as I tried using a Dictionary is much easier. – Shahin Jul 30 '21 at 12:39