# 習題 39: 列表的操作
你已經學過了列表。在你學習“while 循環”的時候,你對列表進行過“追加(append)”操作,而且將列表的內容打印了出來。另外你應該還在加分習題里研究過 Python 文檔,看了列表支持的其他操作。這已經是一段時間以前了,所以如果你不記得了的話,就回到本書的前面再復習一遍把。
找到了嗎?還記得嗎?很好。那時候你對一個列表執行了 append 函數。不過,你也許還沒有真正明白發生的事情,所以我們再來看看我們可以對列表進行什么樣的操作。
當你看到像 mystuff.append('hello') 這樣的代碼時,你事實上已經在 Python 內部激發了一個連鎖反應。以下是它的工作原理:
1. Python 看到你用到了 mystuff ,于是就去找到這個變量。也許它需要倒著檢查看你有沒有在哪里用 = 創建過這個變量,或者檢查它是不是一個函數參數,或者看它是不是一個全局變量。不管哪種方式,它得先找到 mystuff 這個變量才行。
1. 一旦它找到了 mystuff ,就輪到處理句點 . (period) 這個操作符,而且開始查看 mystuff 內部的一些變量了。由于 mystuff 是一個列表,Python 知道mystuff 支持一些函數。
1. 接下來輪到了處理 append 。Python 會將 “append” 和 mystuff 支持的所有函數的名稱一一對比,如果確實其中有一個叫 append 的函數,那么 Python 就會去使用這個函數。
1. 接下來 Python 看到了括號 ( (parenthesis) 并且意識到, “噢,原來這應該是一個函數”,到了這里,它就正常會調用這個函數了,不過這里的函數還要多一個參數才行。
1. 這個額外的參數其實是…… mystuff! 我知道,很奇怪是不是?不過這就是 Python 的工作原理,所以還是記住這一點,就當它是正常的好了。真正發生的事情其實是 append(mystuff,'hello') ,不過你看到的只是 mystuff.append('hello') 。
大部分時候你不需要知道這些細節,不過如果你看到一個像這樣的 Python 錯誤信息的時候,上面的細節就對你有用了:
~~~
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Thing(object):
... def test(hi):
... print "hi"
...
>>> a = Thing()
>>> a.test("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (2 given)
>>>
~~~
就是這個嗎?嗯,這個是我在 Python 命令行下展示給你的一點魔法。你還沒有見過class 不過后面很快就要碰到了。現在你看到 Python 說 test()takesexactly1argument(2given) (test() 只可以接受1個參數,實際上給了兩個)。它意味著 python 把 a.test("hello") 改成了 test(a,"hello") ,而有人弄錯了,沒有為它添加 a 這個參數。
一下子要消化這么多可能有點難度,不過我們將做幾個練習,讓你頭腦中有一個深刻的印象。下面的練習將字符串和列表混在一起,看看你能不能在里邊找出點樂子來:
<table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61</pre> </div> </td> <td class="code"> <div class="highlight"> <pre># create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
# print some states
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
# do it by using the state then cities dict
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]
# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
# print every city in state
print '-' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas', None)
if not state:
print "Sorry, no Texas."
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
</pre> </div> </td> </tr></tbody></table>
### 你應該看到的結果
~~~
----------
NY State has: New York
OR State has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
California is abbreviated CA
Michigan is abbreviated MI
New York is abbreviated NY
Florida is abbreviated FL
Oregon is abbreviated OR
----------
FL has the city Jacksonville
CA has the city San Francisco
MI has the city Detroit
OR has the city Portland
NY has the city New York
----------
California state is abbreviated CA and has city San Francisco
Michigan state is abbreviated MI and has city Detroit
New York state is abbreviated NY and has city New York
Florida state is abbreviated FL and has city Jacksonville
Oregon state is abbreviated OR and has city Portland
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist
~~~
### 加分習題
1. 將每一個被調用的函數以上述的方式翻譯成 Python 實際執行的動作。例如: ''.join(things) 其實是 join('',things) 。
1. 將這兩種方式翻譯為自然語言。例如, ''.join(things) 可以翻譯成“用 ‘ ‘ 連接(join) things”,而 join('',things) 的意思是“為 ‘ ‘ 和 things 調用 join 函數”。這其實是同一件事情。
1. 上網閱讀一些關于“面向對象編程(Object Oriented Programming)”的資料。暈了吧?嗯,我以前也是。別擔心。你將從這本書學到足夠用的關于面向對象編程的基礎知識,而以后你還可以慢慢學到更多。
1. 查一下 Python中的 “class” 是什么東西。不要閱讀關于其他語言的 “class” 的用法,這會讓你更糊涂。
1. dir(something) 和 something 的 class 有什么關系?
1. 如果你不知道我講的是些什么東西,別擔心。程序員為了顯得自己聰明,于是就發明了 Object Oriented Programming,簡稱為 OOP,然后他們就開始濫用這個東西了。如果你覺得這東西太難,你可以開始學一下 “函數編程(functional programming)”。
- 譯者前言
- 前言:笨辦法更簡單
- 習題 0: 準備工作
- 習題 1: 第一個程序
- 習題 2: 注釋和井號
- 習題 3: 數字和數學計算
- 習題 4: 變量(variable)和命名
- 習題 5: 更多的變量和打印
- 習題 6: 字符串(string)和文本
- 習題 7: 更多打印
- 習題 8: 打印,打印
- 習題 9: 打印,打印,打印
- 習題 10: 那是什么?
- 習題 11: 提問
- 習題 12: 提示別人
- 習題 13: 參數、解包、變量
- 習題 14: 提示和傳遞
- 習題 15: 讀取文件
- 習題 16: 讀寫文件
- 習題 17: 更多文件操作
- 習題 18: 命名、變量、代碼、函數
- 習題 19: 函數和變量
- 習題 20: 函數和文件
- 習題 21: 函數可以返回東西
- 習題 22: 到現在你學到了哪些東西?
- 習題 23: 讀代碼
- 習題 24: 更多練習
- 習題 25: 更多更多的練習
- 習題 26: 恭喜你,現在可以考試了!
- 習題 27: 記住邏輯關系
- 習題 28: 布爾表達式練習
- 習題 29: 如果(if)
- 習題 30: Else 和 If
- 習題 31: 作出決定
- 習題 32: 循環和列表
- 習題 33: While 循環
- 習題 34: 訪問列表的元素
- 習題 35: 分支和函數
- 習題 36: 設計和調試
- 習題 37: 復習各種符號
- 習題 38: 閱讀代碼
- 習題 39: 列表的操作
- 習題 40: 字典, 可愛的字典
- 習題 41: 來自 Percal 25 號行星的哥頓人(Gothons)
- 習題 42: 物以類聚
- 習題 43: 你來制作一個游戲
- 習題 44: 給你的游戲打分
- 習題 45: 對象、類、以及從屬關系
- 習題 46: 一個項目骨架
- 習題 47: 自動化測試
- 習題 48: 更復雜的用戶輸入
- 習題 49: 創建句子
- 習題 50: 你的第一個網站
- 習題 51: 從瀏覽器中獲取輸入
- 習題 52: 創建你的 web 游戲
- 下一步
- 老程序員的建議