如何创建可变数量的变量? [英] How do I create a variable number of variables?

查看:114
本文介绍了如何创建可变数量的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中完成变量变量?

How do I accomplish variable variables in Python?

这是一个详尽的手册条目,例如: 变量变量

Here is an elaborative manual entry, for instance: Variable variables

我听说这通常是个坏主意,这是Python中的一个安全漏洞.是真的吗?

I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?

推荐答案

您可以使用词典完成此操作.字典是键和值的存储.

You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.

>>> dct = {'x': 1, 'y': 2, 'z': 3}
>>> dct
{'y': 2, 'x': 1, 'z': 3}
>>> dct["y"]
2

您可以使用变量键名来获得变量变量的效果,而不会带来安全隐患.

You can use variable key names to achieve the effect of variable variables without the security risk.

>>> x = "spam"
>>> z = {x: "eggs"}
>>> z["spam"]
'eggs'

对于您正在考虑做类似事情的情况

For cases where you're thinking of doing something like

var1 = 'foo'
var2 = 'bar'
var3 = 'baz'
...

列表可能比字典更合适.列表代表对象的有序序列,具有整数索引:

a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:

lst = ['foo', 'bar', 'baz']
print(lst[1])           # prints bar, because indices start at 0
lst.append('potatoes')  # lst is now ['foo', 'bar', 'baz', 'potatoes']

对于有序序列,列表比带有整数键的字典更方便,因为列表支持按索引顺序进行迭代,切片append和其他需要笨拙的密钥管理并带有字典的操作.

For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.

这篇关于如何创建可变数量的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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