动态分配变量名? [英] Dynamically assigning variable names?
问题描述
我试图在循环中创建动态变量名称,然后分配适当的值.为了更清楚地演示我在创建此演示代码后的状态:
I am trying to create dynamic variable names as part of a loop and assign then appropriate values. To demonstrate more clearly what I am after I have created this demonstration code:
var1 = ["one","two","three"]
var2 = ["red","blue","green"]
for i in 0 to 2:
var3 = var1[i] #cycle through first list
var4 = var2[i] #cycle through second list
var5 = var3,var4 #make the name of var5 a concatenation of var 3 and var 4
var5 = 1 #assign this dynamic variable name an arbitary value
print var5
我不确定如何处理的是行var5 = var3,var4
.我什至不确定这是否是解决问题的最佳方法.有人可以请
The bit that I am just not sure how to approach is the line var5 = var3,var4
. I'm not even sure that this is the best way to approach the problem. Could someone please:
1)将上面引用的行填入空白处 2)完全建议另一种语法
1) Fill in the blank the line referenced above 2) Suggest an alternative syntax altogether
我需要动态变量名称的原因是在我的for循环中使用的真实代码中,其中循环中的每个数字都附加有不同的条件.抱歉,如果我对方法论有些偏离.
The reason I need dynamic variable names is in my real code I am using for loops where each number in the loop has different conditions attached to it. Apologies if I am a little off beam with my methodology.
我的回答表明我没有明确表达我的要求.我的样本输出必须采用以下格式:
The responses I have had suggest I have not articulated what I require clearly. My sample output needs to be of the format:
one_red = 1
two_blue = 1
three_green = 1
之所以要求它们具有不同的变量名,是因为我最终将把我的输出连接在一起.所以我的最终输出将是:
The reason why I require these to have different variable names is that I will eventually be joining my outputs together. So my final output would be:
111
联接部分暂时不重要,但是重要的是我正在以编程方式在循环中创建变量,每个变量都被分配了自己的值.
The joining section is unimportant for now, but what is important is that I am programatically creating variables in a loop that will each be assigned their own value.
谢谢
推荐答案
使用字典而不是动态分配变量名.另外,您可以使用zip
缩短var3
和var4
行-请参见
Use a dictionary instead of dynamically assigning variable names. Also, you can shorten the var3
and var4
lines using zip
- see Is there a better way to iterate over two lists, getting one element from each list for each iteration?.
到那时,您的代码将类似于:
At that point, your code will look something like:
var1 = ["one","two","three"]
var2 = ["red","blue","green"]
d = {}
for var3, var4 in zip(var1, var2):
d[var3 + var4] = 1
print d
# {'twoblue': 1, 'threegreen': 1, 'onered': 1}
这篇关于动态分配变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!