is there a way to instantiate variables from iterated output in python?

柔情痞子 提交于 2019-12-11 03:17:04

问题


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.



来源:https://stackoverflow.com/questions/24462767/is-there-a-way-to-instantiate-variables-from-iterated-output-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!