简体   繁体   English

在Python中使用循环命名变量

[英]Using a loop in Python to name variables

How do I use a loop to name variables? 如何使用循环命名变量? For example, if I wanted to have a variable double_1 = 2 , double_2 = 4 all the way to double_12 = 24 , how would I write it? 例如,如果我想让变量double_1 = 2double_2 = 4一直到double_12 = 24 ,我该怎么写? I get the feeling it would be something like this: 我感觉会是这样的:

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

Obviously, this doesn't work, but what would be the correct syntax for implementing the looped number into the variable name? 显然,这是行不通的,但是将循环号实现为变量名的正确语法是什么? I haven't coded for a while, but I do remember there was a way to do this. 我已经有一段时间没有编码了,但是我确实记得有一种方法可以做到这一点。

Use a dictionary instead. 请改用字典。 Eg: 例如:

doubles = dict()

for x in range(1, 13):
    doubles[x] = x * 2

Or if you absolutely must do this AND ONLY IF YOU FULLY UNDERSTAND WHAT YOU ARE DOING , you can assign to locals() as to a dictionary: 或者,如果您绝对 必须这样做并且仅在您完全了解正在做的事情的情况下,才可以将locals()分配给字典:

>>> for x in range(1, 13):
...     locals()['double_{0}'.format(x)] = x * 2
... 
>>> double_3
6

There never, ever should be a reason to do this, though - since you should be using the dictionary instead! 但是,永远都不会有这样做的理由-因为您应该改用字典!

expanding my comment: "use a dict. it is exactly why they were created" 扩展我的评论:“使用字典。这正是创建它们的原因”

using defaultdict: 使用defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(int)

using normal dict: 使用普通字典:

>>> d = {}

the rest: 其余的部分:

>>> 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

Although I doubt you really need to do what you want, here's a way: 尽管我怀疑您是否确实需要做您想做的事,但这是一种方法:

namespace = globals()
for x in range(1, 13):
    namespace['double_%d' % x] = x * 2

print double_1
print double_2
   ...
print double_12

globals() returns a dictionary representing the current global symbol table (the dictionary of the current module). globals()返回代表当前全局​​符号表的字典(当前模块的字典)。 As you can see, it's possible to add arbitrary entries to it. 如您所见,可以向其中添加任意条目。

You can use the dict while it don't fit your requirement. 您可以在不符合要求的情况下使用字典。 But I hope it can help you. 但我希望它能对您有所帮助。

var_dic = {}
for x in range(1, 13):
    var_dic["double_%s"% str(x)] = x * 2
print var_dic

As already mentioned, you should use a dict. 如前所述,您应该使用字典。 Here's a nice easy way to create one that meets your requirements. 这是一种创建满足您要求的简便方法。

>>> {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}

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

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