1

I need to generate a number of variables in a loop. I achieved this by using this code:

nBottom=list of initially unknown size
loc=locals()
for k,val in enumerate(nBottom) : loc["imp_local"+str(k)]=700
for k,val in enumerate(nBottom) : loc["imp_global"+str(k)]=600

Now I need to work with them, by creating a dictionary like:

dic1={'imp_local0': 700, ..., 'imp_localn': 700}
dic2={'imp_global0': 700, ..., 'imp_globaln': 700}

How can I do this?

4

2 回答 2

4

不要生成局部变量。只需生成字典:

dict1 = {'imp_local'+str(k):700 for k,val in enumerate(nBottom)}
dict2 = {'imp_global'+str(k):600 for k,val in enumerate(nBottom)}

有关详细信息,请参阅dict comprehensions (PEP 274)

于 2013-05-04T17:32:55.843 回答
1

永远不要使用局部变量来添加变量。特别是因为您实际上希望这些数据最终出现在字典中。只需从一开始就将其添加到字典中:

nBottom=list of initially unknown size
dic1 = {}
dic2 = {}
for k,val in enumerate(nBottom) : dic1["imp_local"+str(k)]=700
for k,val in enumerate(nBottom) : dic2["imp_global"+str(k)]=600

完毕!

于 2013-05-04T17:35:40.377 回答