如何使用循环命名变量?例如,如果我想要变量 double_1 = 2 , double_2 = 4 一直到 double_12 = 24 ,我该如何写它? 我觉得它会是这样的:
for x in range(1, 13):
double_x = x * 2
#I want the x in double_x to count up, e.g double_1, double_2, double_3
显然,这不起作用,但是将循环数字实现到变量名中的正确语法是什么?我没有编码一段时间,但我确实记得有办法做到这一点。
答案 0 :(得分:35)
请改用词典。 E.g:
doubles = dict()
for x in range(1, 13):
doubles[x] = x * 2
或者如果绝对 必须执行 AND ONLY IF YOU FULLY UNDERSTAND WHAT YOU ARE DOING ,您可以为locals()
分配字典:
>>> for x in range(1, 13):
... locals()['double_{0}'.format(x)] = x * 2
...
>>> double_3
6
从来没有应该是这样做的理由 - 因为你应该使用字典!
答案 1 :(得分:6)
扩展我的评论:“使用词典。这正是他们被创造的原因”
使用defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(int)
使用普通字典:
>>> d = {}
其余的:
>>> for x in range(1, 13):
d['double_%02d' % x] = x * 2
>>> for key, value in sorted(d.items()):
print key, value
double_01 2
double_02 4
double_03 6
double_04 8
double_05 10
double_06 12
double_07 14
double_08 16
double_09 18
double_10 20
double_11 22
double_12 24
答案 2 :(得分:4)
虽然我怀疑你真的需要做你想做的事,但这是一种方式:
namespace = globals()
for x in range(1, 13):
namespace['double_%d' % x] = x * 2
print double_1
print double_2
...
print double_12
globals()
返回表示当前全局符号表(当前模块的字典)的字典。如您所见,可以向其中添加任意条目。
答案 3 :(得分:1)
您可以在不符合要求的情况下使用dict。但我希望它可以帮到你。
var_dic = {}
for x in range(1, 13):
var_dic["double_%s"% str(x)] = x * 2
print var_dic
答案 4 :(得分:1)
如前所述,你应该使用dict。这是创建符合您要求的简单方法。
>>> {k:k*2 for k in range(1,13)}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20, 11: 22, 12: 24}