《笨方法学Python》习题39

习题 39: 列表的操作
在文本编辑器中,编辑以下内容并保存到ex39.py文件中,同时在终端中运行该文件:

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]
print stuff.pop()
print ' '.join(stuff)
print stuff[3:5]
print '#'.join(stuff[3:5])

执行结果:

$ 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']
Telephone#Light

加分习题

  1. 将每一个被调用的函数以上述的方式翻译成 Python 实际执行的动作。例 如: ' '.join(things) 其实是 join(' ', things) 。
join(' ',stuff)
join(' ',stuff[3:5])
  1. 将这两种方式翻译为自然语言。例如, 可以翻译成“用 ‘ ‘ 连接(join) things”,而 join(' ', things) 的意思是“为 ‘ ‘ 和 things 调用 join函数”。这其实是同一件事情。
用‘ ’来连接stuff
‘ ’和stuff调用join函数
  1. 上网阅读一些关于“面向对象编程(Object Oriented Programming)”的资料。晕了吧?嗯,我以前也是。别担心。你将从这本书学到足够用的关于面向对象编程的基础知识,而以后你还可以慢慢学到更多。
  2. 查一下 Python 中的 “class” 是什么东西。不要阅读关于其他语言的 “class” 的用法,这会让你更糊涂。
  3. dir(something)和something的 class 有什么关系?
  4. 如果你不知道我讲的是些什么东西,别担心。程序员为了显得自己聪明,于是就发明了 Opject Oriented Programming,简称为 OOP,然后他们就开始滥用这个东西 了。如果你觉得这东西太难,你可以开始学一下 “函数编程(functional programming)”。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。