带有字符串索引的 Python 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3765533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:39:02  来源:igfitidea点击:

Python Array with String Indices

pythonarrayslistdictionary

提问by Petey B

Is it possible to use strings as indices in an array in python?

是否可以将字符串用作python数组中的索引?

For example:

例如:

myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]

采纳答案by miku

What you want is called an associative array. In python these are called dictionaries.

您想要的称为关联数组。在 python 中,这些被称为字典

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

字典有时在其他语言中被称为“关联记忆”或“关联数组”。与由一系列数字索引的序列不同,字典由键索引,键可以是任何不可变类型;字符串和数字始终可以是键。

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

创建上述 dict 的替代方法:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

访问值:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

获取密钥(在 Python v2 中):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docsand PEP 3106for details).

在 Python 3 中,您将获得一个dict_keys,它是一个视图,效率更高(有关详细信息,请参阅视图文档PEP 3106)。

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 


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 字典的内部结构,我推荐这个大约 25 分钟的视频演示:https: //www.youtube.com/watch?v=C4Kc8xzcA68。它被称为“强大的词典”。

回答by gaefan

Even better, try an OrderedDict(assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

更好的是,尝试使用OrderedDict(假设您想要列表之类的东西)。比普通字典更接近列表,因为键有顺序,就像列表元素有顺序一样。使用常规字典,键具有任意顺序。

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

请注意,这在 Python 3 和 2.7 中可用。如果你想使用早期版本的 Python,你可以找到可安装的模块来做到这一点。