Python的字符串的数组指数 [英] Python Array with String Indices

查看:203
本文介绍了Python的字符串的数组指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在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屋!

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