我有一堆变量
myvar1='say1'
myvar2='say2'
myvar3='say3'
myvar4='say4'
myvar4='say5'
Run Code Online (Sandbox Code Playgroud)
要打印它们,我使用for循环
for i in (range 1,6):
print('{}-{}'.format(i,vars()['myvar'+str(i)]))
Run Code Online (Sandbox Code Playgroud)
这会产生
1-say1
2-say2
3-say3
4-say4
5-say5
Run Code Online (Sandbox Code Playgroud)
我的问题很简单,这是最好的方法(我的意思是var()[]部分).我倾向于使用这种东西(不只是用于打印变量值...)而且我认为它看起来很时髦.我一直在寻找其他的例子,我真的没有找到任何.那么,有更好的方法吗?
所以最终我想知道从变量中的变量名获取值的最佳方法是什么?
So, is there a better way
在课程中,为什么不只是使用一个列表或者如果你需要更多的estoric编号,请使用字典(或者如果顺序很重要,请使用OrderedDict`?
带列表的示例代码
>>> myvar = ['say1','say2','say3','say4','say5']
>>> for index, var in enumerate(myvar, 1):
print "{}-{}".format(index ,var)
1-say1
2-say2
3-say3
4-say4
5-say5
Run Code Online (Sandbox Code Playgroud)
使用OrderedDict的示例代码
>>> from collections import OrderedDict
>>> myvar = OrderedDict(
[('a','say'),
('b','say2'),
('c','say3'),
('d','say4'),
('e','say5')])
>>> for key, value in myvar.items():
print "{}-{}".format(key,value)
a-say
b-say2
c-say3
d-say4
e-say5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |