简体   繁体   English

如何分配名称是即时生成的python变量?

[英]how to assign a python variable whose name is generated on-the-fly?

Say I want to do the following: 假设我要执行以下操作:

name = 1.2

The thing is that the literal name of 'name' is provided on-the-fly (it could be 'mike=1.2', 'john=1.2',...) 问题是即时提供“名称”的字面名称(它可以是“ mike = 1.2”,“ john = 1.2”,...)

Hope I explained my question, and thanks in advance for any hint. 希望我能解释我的问题,并在此先感谢您的提示。

You can use globals() or locals() depending on the scope needed: 您可以根据需要的范围使用globals()locals()

>>> globals()['foo'] = 'bar'
>>> foo
'bar'

If you're asking this questions, however, it means you're doing something wrong - generating variables is essentially a bad idea. 但是,如果您问这个问题,则意味着您做错了什么- 生成变量本质上是一个坏主意。 You should use structures such as a dictionary for this. 为此,您应该使用诸如字典之类的结构。

Here is an example of how to do this as a dictionary. 这是一个如何作为字典的示例。

>>> people = {}
>>> people['mike'] = 1
>>> people['john'] = 2
>>> people['mike']
1
>>> people['john']
2
>>> print people
{'mike': 1, 'john': 2}

Also see the documentation here and here 另请参见此处此处的文档

you could do 你可以做

globals()['yourvariables'] = variable

This adds the variable to the global namespace. 这会将变量添加到全局名称空间。 I am not going to comment on whether it is a good idea or a bad one. 我不会评论这是一个好主意还是一个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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