笨办法学Python学习笔记 练习25

来源:互联网 发布:计算机机房网络维护ppt 编辑:程序博客网 时间:2024/06/11 06:28
def break_words(stuff):    """This function will break up words for us."""    words = stuff.split(' ')    return wordsdef sort_words(words):    """Sorts the words."""    return sorted(words)def print_first_word(words):    """Prints the fist ord after popping it off."""    word = words.pop(0)    print worddef print_last_word(words):    """Prints the last word after popping it off."""    word = words.pop(-1)    print worddef 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)


这一节的练习很奇怪,没有输出,所以这节的代码是写了一个可以调用的模组,下面三引号中的内容为注释,表明函数功能。

从输出结果来看,首先import调用模组,然后创建了一个sentence变量,用break_words函数将句子分成单词(这其实是个列表,但是列表是啥?)。

之后将单词排序,得到一个新的列表。

打印words列表中的第一个单词(pop是列表的一种操作方法,删除并返回值,0代表首位,-1代表末尾)。

所以第二次打印words列表时,All和wait消失不见了。

接着是打印sorted_words的首位和末尾的值,同样的,打印了之后,All和who也不见了。

然后调用sort_sentence重新对word列表赋值。

后面……就都一样了。


运行结果:


0 0
原创粉丝点击