在 Python 中使用循环来命名变量 [英] Using a loop in Python to name variables

查看:74
本文介绍了在 Python 中使用循环来命名变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用循环来命名变量?例如,如果我想要一个变量 double_1 = 2, double_2 = 4 一直到 double_12 = 24,我该怎么做?写吗?

我感觉应该是这样的:

 for x in range(1, 13):double_x = x * 2# 我希望 double_x 中的 x 向上计数,例如 double_1、double_2、double_3

显然,这行不通,但是将循环数字实现到变量名称中的正确语法是什么?我有一段时间没有编码了,但我记得有一种方法可以做到这一点.

解决方案

改用字典.例如:

doubles = dict()对于范围内的 x(1, 13):双打[x] = x * 2

或者如果您绝对必须这样做并且只有当您完全理解您在做什么,您才能将locals() 分配给字典:

<预><代码>>>>对于范围内的 x(1, 13):... locals()['double_{0}'.format(x)] = x * 2...>>>double_36

永远,永远应该是这样做的理由,因为你应该使用字典代替!

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆