你已经学过了列表。在你学习“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