1. 程式人生 > >笨辦法學Python(四十)

笨辦法學Python(四十)

變量名 有用 play 有一個 結果 註意 roi 做了 理解

習題 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(四十)