问题描述
是否可以在python中使用字符串作为数组中的索引?
Is it possible to use strings as indices in an array in python?
例如:
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]
推荐答案
你想要的是一个关联数组.在 Python 中,这些被称为 dictionaries.
What you want is called an associative array. In python these are called dictionaries.
字典有时在其他语言中被称为关联存储器"或关联数组".与由一系列数字索引的序列不同,字典由键索引,键可以是任何不可变类型;字符串和数字始终可以是键.
myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"
创建上述字典的另一种方法:
Alternative way to create the above dict:
myDict = {"john": "johns value", "jeff": "jeffs value"}
访问值:
print(myDict["jeff"]) # => "jeffs value"
获取密钥(在 Python v2 中):
Getting the keys (in Python v2):
print(myDict.keys()) # => ["john", "jeff"]
在 Python 3 中,您将获得一个 dict_keys
,它是一个视图并且效率更高(请参阅 查看文档 和 PEP 3106 了解详情).
In Python 3, you'll get a dict_keys
, which is a view and a bit more efficient (see views docs and PEP 3106 for details).
print(myDict.keys()) # => dict_keys(['john', 'jeff'])
如果你想了解 Python 字典的内部结构,我推荐这个约 25 分钟的视频演示:https://www.youtube.com/watch?v=C4Kc8xzcA68.它被称为强大的词典".
If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".
这篇关于带有字符串索引的 Python 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!