如何创建可变变量? [英] How do I create variable variables?

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

问题描述

如何在 Python 中实现可变变量?

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

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

解决方案

您可以使用 dictionaries 来实现这一点.字典是键和值的存储.

<预><代码>>>>dct = {'x':1,'y':2,'z':3}>>>直流电{'y':2,'x':1,'z':3}>>>dct["y"]2

可以使用变量键名来实现变量变量的效果,没有安全风险.

<预><代码>>>>x = "垃圾邮件">>>z = {x:鸡蛋"}>>>z[垃圾邮件"]'蛋'

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

var1 = 'foo'var2 = '酒吧'var3 = 'baz'...

列表可能比字典更合适.一个列表表示一个有序的对象序列,带有整数索引:

lst = ['foo', 'bar', 'baz']print(lst[1]) # 打印 bar,因为索引从 0 开始lst.append('potatoes') # lst 现在是 ['foo', 'bar', 'baz', 'potatoes']

对于有序序列,lists比带有整数键的dicts更方便,因为lists支持按索引顺序迭代,slicingappend 和其他需要使用 dict 进行笨拙密钥管理的操作.

How do I accomplish variable variables in Python?

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

I hear this is a bad idea in general though, and it is a security hole in PHP. 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']

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天全站免登陆