如標(biāo)題一樣,這課的知識(shí)點(diǎn)確時(shí)比較多,先貼上代碼
#coding=utf-8
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):
"""Print the last word atfer poping 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 = sort_sentence(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)
從代碼來一點(diǎn)點(diǎn)的往下扒
words = stuff.split(' ')
- python split()方法:通過指定的分隔符對(duì)字符中進(jìn)行切片,split()有兩個(gè)參數(shù)比如,str.split(" ", 2)可以這樣理解,把str按空格分隔一次,返回列表格式,代碼中沒有數(shù)字參數(shù),就是分隔到底
sorted(words)
- sorted()方法有兩種用法
x = [3,2,5,4]
x.sort()
x = [3,2,5,4]
sorted(x)
后者會(huì)生成一個(gè)列表副本,前者直接覆蓋本來的列表
word = words.pop(0)
python pop()方法:從列表中移除并返回最后一個(gè)對(duì)象,參數(shù)可以選擇對(duì)象的索引,默認(rèn)是最后一個(gè)對(duì)象被返回且被刪除
補(bǔ)充一個(gè)降序排列方法reverse()
這課有意思的地方就是,在python解析器中,以交互的方式和自己寫的這個(gè)ex25.py交流,需要的就是在交互前先執(zhí)行import ex25,是不是有點(diǎn)想起了之前引用的模塊,暫進(jìn)可以這么理解,我們都是在引用某個(gè)模塊中的某種方法或是函數(shù),比如這課的代碼,import ex25后就可以調(diào)用里面的函數(shù),使用方式是ex25.bread_words()那么,更好玩的是,你可以查看你自己寫的代碼的幫助文檔,在windows powershell鍵入python -m pydoc ex25
也可以查看ex25里函數(shù)的幫助文檔,鍵入pyhton -m pydoc ex25.break_words

0000.png
看看幫助文檔中顯示的是代碼哪部分