码迷,mamicode.com
首页 > 编程语言 > 详细

笨办法学Python(四十)

时间:2017-10-01 23:05:23      阅读:364      评论:0      收藏:0      [点我收藏+]

标签:log   bsp   lan   doc   列表   删除   cisc   习题   一个   

习题 40: 字典, 可爱的字典

    接下来我要教你另外一种让你伤脑筋的容器型数据结构,因为一旦你学会这种容器,你将拥有超酷的能力。这是最有用的容器:字典(dictionary)。

    Python 将这种数据类型叫做 “dict”,有的语言里它的名称是 “hash”。这两种名字我都会用到,不过这并不重要,重要的是它们和列表的区别。你看,针对列表你可以做这样的事情:

1 >>> things = [a, b, c, d]
2 >>> print things[1]
3 b
4 >>> things[1] = z
5 >>> print things[1]
6 z
7 >>> print things
8 [a, z, c, d]
9 >>>

    你可以使用数字作为列表的索引,也就是你可以通过数字找到列表中的元素。而 dict 所作的,是让你可以通过任何东西找到元素,不只是数字。是的,字典可以将一个物件和另外一个东西关联,不管它们的类型是什么,我们来看看:

 1 >>> stuff = {name: Zed, age: 36, height: 6*12+2}
 2 >>> print stuff[name]
 3 Zed
 4 >>> print stuff[age]
 5 36
 6 >>> print stuff[height]
 7 74
 8 >>> stuff[city] = "San Francisco"
 9 >>> print stuff[city]
10 San Francisco
11 >>>

    你将看到除了通过数字以外,我们还可以用字符串来从字典中获取 stuff ,我们还可以用字符串来往字典中添加元素。当然它支持的不只有字符串,我们还可以做这样的事情:

 1 >>> stuff[1] = "Wow"
 2 >>> stuff[2] = "Neato"
 3 >>> print stuff[1]
 4 Wow
 5 >>> print stuff[2]
 6 Neato
 7 >>> print stuff
 8 {city: San Francisco, 2: Neato,
 9     name: Zed, 1: Wow, age: 36,
10     height: 74}
11 >>>

    在这里我使用了两个数字。其实我可以使用任何东西,不过这么说并不准确,不过你先这么理解就行了。

    当然了,一个只能放东西进去的字典是没啥意思的,所以我们还要有删除物件的方法,也就是使用 del 这个关键字:

1 >>> del stuff[city]
2 >>> del stuff[1]
3 >>> del stuff[2]
4 >>> stuff
5 {name: Zed, age: 36, height: 74}
6 >>>

    接下来我们要做一个练习,你必须非常仔细,我要求你将这个练习写下来,然后试着弄懂它做了些什么。这个练习很有趣,做完以后你可能会有豁然开朗的感觉。

技术分享
 1 cities = {CA: San Francisco, MI: Detroit,
 2                      FL: Jacksonville}
 3 
 4 cities[NY] = New York
 5 cities[OR] = Portland
 6 
 7 def find_city(themap, state):
 8     if state in themap:
 9         return themap[state]
10     else:
11         return "Not found."
12 
13 # ok pay attention!
14 cities[_find] = find_city
15 
16 while True:
17     print "State? (ENTER to quit)",
18     state = raw_input("> ")
19 
20     if not state: break
21 
22     # this line is the most important ever! study!
23     city_found = cities[_find](cities, state)
24     print city_found
View Code

Warning

    注意到我用了 themap 而不是 map 了吧?这是因为 Python 已经有一个函数称作 map 了,所以如果你用 map 做变量名,你后面可能会碰到问题。

你应该看到的结果

 技术分享

 

 

加分习题

  1. 在 Python 文档中找到 dictionary (又被称作 dicts, dict)的相关的内容,学着对 dict 做更多的操作。
  2. 找出一些 dict 无法做到的事情。例如比较重要的一个就是 dict 的内容是无序的,你可以检查一下看看是否真是这样。
  3. 试着把 for-loop 执行到 dict 上面,然后试着在 for-loop 中使用 dict 的 items() 函数,看看会有什么样的结果。

笨办法学Python(四十)

标签:log   bsp   lan   doc   列表   删除   cisc   习题   一个   

原文地址:http://www.cnblogs.com/yllinux/p/7617952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!