在python中可以使用for作为变量名对吗,在Python中使用循环来命名变量

博客讨论了如何在Python中通过循环创建带有动态索引的变量,如`double_1`, `double_2`等。作者建议使用字典代替直接创建变量,提供了一种使用字典的解决方案,并指出在必须创建动态变量的情况下,可以利用`locals()`函数结合字符串格式化来实现。但同时强调,通常不推荐这种做法,应优先考虑使用字典来存储数据。
摘要由CSDN通过智能技术生成

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

Or if you absolutely must do this

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值