使用循环创建多个变量 [英] Using a loop to create multiple variables
本文介绍了使用循环创建多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我需要创建 5 个变量.由于这在未来可能需要调整,我使用了一个循环.
i = 0对于范围内的 j(5):我 += 1w[i] = 函数(i)#结果是:w1 = 函数(1)w2 = 函数(2)#等等...
我知道上面的代码不正确.是否可以使用循环来创建不同的变量?
解决方案
要创建多个变量,您可以使用如下所示的方法,您可以使用 for 循环并存储一对键值,其中键是不同的变量名称
d={} #空字典for x in range(1,10): #for 循环d["string{0}".format(x)]="Variable1";
<块引用>
输出看起来像
{'string1': 'Variable1', 'string2': 'Variable1','string3': 'Variable1', 'string4': 'Variable1', 'string5':'Variable1', 'string6':'变量1','string7':'变量1','string8':'变量1','string9':'变量1'}
Let's say I need to make 5 variables. Since this may need to be adjusted in the future, I'm using a loop.
i = 0
for j in range(5):
i += 1
w[i] = function(i)
#results in:
w1 = function(1)
w2 = function(2)
#etc...
I know the code above is incorrect. Is it possible to use a loop to create different variables?
解决方案
To create multiple variables you can use something like below, you use a for loop and store a pair of key-value, where key is the different variable names
d={} #empty dictionary
for x in range(1,10): #for looping
d["string{0}".format(x)]="Variable1"
The output looks like
{'string1': 'Variable1', 'string2': 'Variable1','string3': 'Variable1', 'string4': 'Variable1', 'string5':'Variable1', 'string6': 'Variable1', 'string7': 'Variable1','string8': 'Variable1', 'string9': 'Variable1'}
这篇关于使用循环创建多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文