Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著
的学习思路和理解,如有不如之处,望指出!!!
本节我们利用前面学习的Python函数(def
)知识,做一个简单的模块(module),然后我们从外部调用这个模块的函数。
源代码
# ex25.py
def break_words(stuff):
"""
This function will break up words for us.
"""
words=stuff.split(' ')
return words
def sort_words(words):
"""
sorts the words.
"""
return sorted (words)
def print_first_word(words):
"""
prints the first word after popping it off.
"""
word=words.pop(0)
print word
def print_last_word(words):
"""
prints the last word after popping it off.
"""
word=words.pop(-1)
print word
def sort_sentence(sentence):
"""
takes in a full sentence and returns the sorted words.
"""
words=break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""
prints the first and last words of the sentence.
"""
words=break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""
sorts the words then prints the first and last one.
"""
words=sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
我们来分析下以上代码中,每一个函数的作用
- 把句子中的字母分离,然后返回到
words
中 - 把
words
中的字母重新排序,然后返回到sorted_words
中 - 输出
words
中存储的第一个字母 - 输出
words
中存储的最后一个字母 - 把重新的排序的字母组成一个句子,然后返回到
sorted_words
中 - 输出
words
的第一个和最后一个字母 - 输出
sorted_words
的第一个和最后一个字母
你应该看到的结果
注意:我对上面这个代码文件的命名是
test13.py
我们来分析下编译时每一句的作用是什么?
- 在第5行,将
test13.py
执行了import
,和我们前面介绍的import
作用是一样的。在import
的时候是不需要加.py
后缀的。把test13.py
当成一个模块module
来使用,在这个模块里定义的函数是可以直接调用的。 - 第6行创建了一个语句
- 第7行使用
test13
调用第一个函数test13.break_words
。其中的.
符号可以告诉Python:“我要运行test13
模块里那个叫break_words
的函数。” - 第8行只是输入
words
,而Python会在第9行打印出words
这个变量里的内容,输出的结果是一个列表,后面小节会讲到的 - 第10~11行使用
test13.sort_words
来得到一个排序过的句子 - 第13~16行使用
test13.print_first_word
和test13.print_last_word
将第一个词和最后一个词打印出来 - 第17行和第8行的作用是一样的,输出
words
这个变量里的内容 - 第19行和第21行的作用同上,是打印出第一个词和最后一个词
- 第23行和第8行的作用类似
- 第25行调用函数
test13.sort_sentence
- 剩下几行的作用都和前面的作用都类似了
本节要掌握的知识
pop()
函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
标准写法:
list.pop(obj=list[-1])
参数:
obj -- 可选参数,要移除列表元素的对象。
默认参数为-1,是最后一个元素
参数0,是第一个元素
示例:
aList = [123, 'xyz', 'zara', 'abc']
print "A List : ", aList.pop(-1)
# 参数 -1 指向的是 abc
print "B List : ", aList.pop(0)
# 参数 0 指向的是 123
print "C List : ", aList.pop(1)
# 参数 1 指向的是 xyz
print "D List : ", aList.pop(2)
# 参数 2 指向的是 zara
这是**《笨方法学Python》**的第十三篇文章
希望自己可以坚持下去
希望你也可以坚持下去