ex25知識(shí)點(diǎn)較多的一課

如標(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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容