Python的字符串的数组指数 [英] Python Array with String Indices
问题描述
是否有可能在Python中使用字符串作为索引的数组?
例如:
myArray的= []
myArray的[约翰] =嫖客值
myArray的[杰夫] =杰夫斯值
打印myArray的[约翰]
字典在其他语言中有时会发现为联想记忆或关联数组。不同的序列,这是由一系列的数字索引,词典是由按键,它可以是任意不可变类型索引;字符串和数字总是可以密钥。
块引用>myDict = {}
myDict [约翰] =嫖客值
myDict [杰夫] =杰夫斯值另类的方式来创建上述字典:
myDict = {约翰:约翰的价值,杰夫:杰夫斯值}
访问值:
打印myDict [杰夫]#=> 杰夫斯价值
获取键(在Python V2):
打印myDict.keys()#=> [约翰,杰夫]
如果您想了解Python字典的内部,我建议这个〜25分钟的视频presentation:的https:/ /www.youtube.com/watch?v=C4Kc8xzcA68 。这就是所谓的强大辞典。
Is it possible to use strings as indices in an array in python?
For example:
myArray = [] myArray["john"] = "johns value" myArray["jeff"] = "jeffs value" print myArray["john"]
解决方案What you want is called an associative array. In python these are called dictionaries.
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:
myDict = {"john": "johns value", "jeff": "jeffs value"}
Accessing values:
print myDict["jeff"] # => "jeffs value"
Getting the keys (in Python v2):
print myDict.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的字符串的数组指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!