在循环中如何创建不同的变量名? [英] How do you create different variable names while in a loop?
本文介绍了在循环中如何创建不同的变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
出于示例目的...
for x in range(0,9):
string'x' = "Hello"
所以我最终得到了string1,string2,string3 ...都等于"Hello"
So I end up with string1, string2, string3... all equaling "Hello"
推荐答案
当然可以;它称为词典:
d={}
for x in range(1,10):
d["string{0}".format(x)]="Hello"
In [7]: d["string5"]
Out[7]: 'Hello'
In [8]: d
Out[8]:
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}
我说的有点难以理解,但实际上将一个值与另一个值相关联的最佳方法是字典.这就是它的设计目的!
I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!
这篇关于在循环中如何创建不同的变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文