你已經學過了列表。在你學習“while 循環”的時候,你對列表進行過“追加(append)”操作,而且將列表的內容打印了出來。另外你應該還在加分習題里研究過 Python 文檔,看了列表支持的其他操作。這已經是一段時間以前了,所以如果你不記得了的話,就回到本書的前面再復習一遍把。
找到了嗎?還記得嗎?很好。那時候你對一個列表執行了 append 函數。不過,你也許還沒有真正明白發生的事情,所以我們再來看看我們可以對列表進行什么樣的操作。
當你看到像 mystuff.append('hello') 這樣的代碼時,你事實上已經在 Python 內部激發了一個連鎖反應。以下是它的工作原理:
大部分時候你不需要知道這些細節,不過如果你看到一個像這樣的 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() takes exactly 1 argument (2 given) (test() 只可以接受1個參數,實際上給了兩個)。它意味著 python 把 a.test("hello") 改成了 test(a, "hello") ,而有人弄錯了,沒有為它添加 a 這個參數。
一下子要消化這么多可能有點難度,不過我們將做幾個練習,讓你頭腦中有一個深刻的印象。下面的練習將字符串和列表混在一起,看看你能不能在里邊找出點樂子來:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There's %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!
|
$ python ex39.py
Wait there's not 10 things in that list, let's fix that.
Adding: Boy
There's 7 items now.
Adding: Girl
There's 8 items now.
Adding: Banana
There's 9 items now.
Adding: Corn
There's 10 items now.
There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar',
'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
Telephone#Light