is there a way to instantiate variables from itera

2019-07-16 09:58发布

问题:

Say I have a list my_list = ['a','b','c'] and I have a set of values my_values = [1,2,3]

Is there a way to iterate through my list and set the values of my_list equal to my_values

for i in range(len(my_list)):

    ## an operation that instantiates my_list[i] as the variable a = my_values[i]

...
>>> print a
1

I just want to do this without copying the text of file that holds the program to a new file, inserting the new lines as strings where they need to go in the program. I'd like to skip the create, rename, destroy, file operations if possible, as I'm dealing with pretty large sets of stuff.

回答1:

This is probably hackery that you shouldn't do, but since the globals() dict has all the global variables in it, you can add them to the global dict for the module:

>>> my_list = ['a','b','c']
>>> my_values = [1,2,3]
>>> for k, v in zip(my_list, my_values):
...     globals()[k] = v
... 
>>> a
1
>>> b
2
>>> c
3

But caveat emptor, best not to mix your namespace with your variable values. I don't see anything good coming of it.

I recommend using a normal dict instead to store your values instead of loading them into the global or local namespace.