多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 习题 40: 字典, 可爱的字典 接下来我要教你另外一种让你伤脑筋的容器型数据结构,因为一旦你学会这种容器,你将拥有超酷的能力。这是最有用的容器:字典(dictionary)。 Python 将这种数据类型叫做 “dict”,有的语言里它的名称是 “hash”。这两种名字我都会用到,不过这并不重要,重要的是它们和列表的区别。你看,针对列表你可以做这样的事情: ~~~ >>> things = ['a', 'b', 'c', 'd'] >>> print things[1] b >>> things[1] = 'z' >>> print things[1] z >>> print things ['a', 'z', 'c', 'd'] >>> ~~~ 你可以使用数字作为列表的索引,也就是你可以通过数字找到列表中的元素。而 dict 所作的,是让你可以通过任何东西找到元素,不只是数字。是的,字典可以将一个物件和另外一个东西关联,不管它们的类型是什么,我们来看看: ~~~ >>> stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2} >>> print stuff['name'] Zed >>> print stuff['age'] 36 >>> print stuff['height'] 74 >>> stuff['city'] = "San Francisco" >>> print stuff['city'] San Francisco >>> ~~~ 你将看到除了通过数字以外,我们还可以用字符串来从字典中获取 stuff ,我们还可以用字符串来往字典中添加元素。当然它支持的不只有字符串,我们还可以做这样的事情: ~~~ >>> stuff[1] = "Wow" >>> stuff[2] = "Neato" >>> print stuff[1] Wow >>> print stuff[2] Neato >>> print stuff {'city': 'San Francisco', 2: 'Neato', 'name': 'Zed', 1: 'Wow', 'age': 36, 'height': 74} >>> ~~~ 在这里我使用了两个数字。其实我可以使用任何东西,不过这么说并不准确,不过你先这么理解就行了。 当然了,一个只能放东西进去的字典是没啥意思的,所以我们还要有删除物件的方法,也就是使用 del 这个关键字: ~~~ >>> del stuff['city'] >>> del stuff[1] >>> del stuff[2] >>> stuff {'name': 'Zed', 'age': 36, 'height': 74} >>> ~~~ 接下来我们要做一个练习,你必须非常仔细,我要求你将这个练习写下来,然后试着弄懂它做了些什么。这个练习很有趣,做完以后你可能会有豁然开朗的感觉。 <table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre> 1&#13; 2&#13; 3&#13; 4&#13; 5&#13; 6&#13; 7&#13; 8&#13; 9&#13; 10&#13; 11&#13; 12&#13; 13&#13; 14&#13; 15&#13; 16&#13; 17&#13; 18&#13; 19</pre> </div> </td> <td class="code"> <div class="highlight"> <pre>class Song(object):&#13; &#13; def __init__(self, lyrics):&#13; self.lyrics = lyrics&#13; &#13; def sing_me_a_song(self):&#13; for line in self.lyrics:&#13; print line&#13; &#13; happy_bday = Song(["Happy birthday to you",&#13; "I don't want to get sued",&#13; "So I'll stop right there"])&#13; &#13; bulls_on_parade = Song(["They rally around the family",&#13; "With pockets full of shells"])&#13; &#13; happy_bday.sing_me_a_song()&#13; &#13; bulls_on_parade.sing_me_a_song()&#13; </pre> </div> </td> </tr></tbody></table> Warning 注意到我用了 themap 而不是 map 了吧?这是因为 Python 已经有一个函数称作 map 了,所以如果你用 map 做变量名,你后面可能会碰到问题。 ### 你应该看到的结果 ~~~ Happy birthday to you I don't want to get sued So I'll stop right there They rally around the family With pockets full of shells ~~~ ### 加分习题 1. 在 Python 文档中找到 dictionary (又被称作 dicts, dict)的相关的内容,学着对 dict 做更多的操作。 1. 找出一些 dict 无法做到的事情。例如比较重要的一个就是 dict 的内容是无序的,你可以检查一下看看是否真是这样。 1. 试着把 for-loop 执行到 dict 上面,然后试着在 for-loop 中使用 dict 的 items() 函数,看看会有什么样的结果。