在 python 中动态生成变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4010840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
generating variable names on fly in python
提问by Curious2learn
Is there a way I can generate variable names in python in a loop and assign values to them? For example, if I have
有没有办法可以在python中循环生成变量名并为它们赋值?例如,如果我有
prices = [5, 12, 45]
I want
我想要
price1 = 5
price2 = 12
price3 = 45
Can I do this in a loop or something instead of manually assigning price1 = prices[0], price2 = prices[1]etc.
我可以在一个循环或某事做,而不是手动分配price1 = prices[0],price2 = prices[1]等等。
Thank you.
谢谢你。
EDIT
编辑
Many people suggested that I write a reason for requiring this. First, there have been times where I have thought this may be more convenient than using a list...I don't remember exactly when, but I think I have thought of using this when there are many levels of nesting. For example, if one has a list of lists of lists, defining variables in the above way may help reduce the level of nesting. Second, today I thought of this when trying to learn use of Pytables. I just came across Pytables and I saw that when defining the structure of a table, the column names and types are described in the following manner:
很多人建议我写一个要求这个的理由。首先,有时我认为这可能比使用列表更方便......我不记得确切的时间,但我想当有很多嵌套级别时我想过使用它。例如,如果有一个列表列表,以上述方式定义变量可能有助于降低嵌套级别。第二,今天尝试学习使用Pytables的时候想到了这个。刚接触到Pytables,看到在定义表的结构时,列名和类型是这样描述的:
class TableFormat(tables.IsDescription):
firstColumnName = StringCol(16)
secondColumnName = StringCol(16)
thirdColumnName = StringCol(16)
If I have 100 columns, typing the name of each column explicitly seems a lot of work. So, I wondered whether there is a way to generate these column names on the fly.
如果我有 100 列,那么明确地输入每列的名称似乎需要很多工作。所以,我想知道是否有办法动态生成这些列名。
回答by Tim ?as
Though I don't see much point, here it is:
虽然我没有看到太多的意义,但这里是:
for i in xrange(0, len(prices)):
exec("price%d = %s" % (i + 1, repr(prices[i])));
回答by kanaka
If you really want to create them on the fly you can assign to the dict that is returned by either globals()or locals()depending on what namespace you want to create them in:
如果你真的想动态创建它们,你可以分配给由两者返回的 dictglobals()或者locals()取决于你想在什么命名空间中创建它们:
globals()['somevar'] = 'someval'
print somevar # prints 'someval'
But I wouldn't recommend doing that. In general, avoid global variables. Using locals()often just obscures what you are really doing. Instead, create your own dict and assign to it.
但我不建议这样做。一般来说,避免使用全局变量。locals()经常使用只会掩盖你真正在做什么。相反,创建自己的字典并分配给它。
mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']
Learn the python zen; run this and grok it well:
学习蟒蛇禅;运行它并很好地理解它:
>>> import this
回答by Stefano Borini
On an object, you can achieve this with setattr
在一个对象上,你可以用 setattr
>>> class A(object): pass
>>> a=A()
>>> setattr(a, "hello1", 5)
>>> a.hello1
5
回答by PolyGeo
Another example, which is really a variation of another answer, in that it uses a dictionary too:
另一个例子,它实际上是另一个答案的变体,因为它也使用字典:
>>> vr={}
... for num in range(1,4):
... vr[str(num)] = 5 + num
...
>>> print vr["3"]
8
>>>
回答by Pranjay Kaparuwan
I got your problem , and here is my answer:
我遇到了你的问题,这是我的答案:
prices = [5, 12, 45]
list=['1','2','3']
for i in range(1,3):
vars()["prices"+list[0]]=prices[0]
print ("prices[i]=" +prices[i])
so while printing:
所以在打印时:
price1 = 5
price2 = 12
price3 = 45
回答by Leo Zhang
bit long, it works i guess...
有点长,我猜它有效......
prices = [5, 12, 45]
names = []
for i, _ in enumerate(prices):
names.append("price"+str(i+1))
dict = {}
for name, price in zip(names, prices):
dict[name] = price
for item in dict:
print(item, "=", dict[item])

