在Python中使用循环来命名变量 [英] Using a loop in Python to name variables
问题描述
如何使用循环来命名变量?例如,如果我想变量 double_1 = 2 , double_2 = 4 一直到 double_12 = 24 ,我该如何写它?
我感觉它会是这样的:
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? 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. E.g:
doubles = dict()
for x in range(1, 13):
doubles[x] = x * 2
或者 必须执行 只有完全了解你正在做什么 ,你可以分配给 locals()
作为字典:
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:
>>> 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!
这篇关于在Python中使用循环来命名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!