Python数组与字符串索引 [英] Python Array with String Indices

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

问题描述

可以在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"]


推荐答案

一个href =http://en.wikipedia.org/wiki/Associative_array =noreferrer>关联数组。在python这些被称为词典

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"

以上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字典内部,我推荐这个〜25分钟的视频演示: https:// www .youtube.com /手表?ν= 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数组与字符串索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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