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.""" #打印后的第一個(gè)詞出現(xiàn)
word = words.pop(0)
print (word)
def print_last_word(words):
"""Prints the last word after popping it off.""" #打印后的最后一個(gè)詞出現(xiàn)
word = words.pop(-1)
print (word)
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words.""" #接受一個(gè)完整句子并返回排序的單詞
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence.""" #打印第一個(gè)和最后一個(gè)單詞的句子
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.""" #單詞然后打印第一個(gè)和最后一個(gè)
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
1.stuff.split(’ ‘),以空格為標(biāo)志分割字符串,默認(rèn)全部分割,可以在括號(hào)里”后面指定參數(shù)以使解釋器按規(guī)定次數(shù)分割。
比如stuff.split(”,1)只分割一次,分割結(jié)果是’All’和’good things come to those who wait.’
2.sorted(words),以字母表順序?yàn)橐罁?jù)將words變量所包含的字符串中的英文單詞進(jìn)行排序,英文句號(hào)在該過(guò)程中將被舍棄。
3.word = words.pop(0),彈出一個(gè)元素后關(guān)閉,括號(hào)內(nèi)的參數(shù)表示彈出元素的位置。0代表第一個(gè),-1代表最后一個(gè)。暫不清楚單位是不是之前類(lèi)似的字節(jié),之前碰到位置參數(shù)時(shí),數(shù)字代表的是第幾個(gè)字節(jié)數(shù)。請(qǐng)記住這種用法,也記住這個(gè)疑問(wèn)。稍后再碰到一些具體的例子就能理解了。
4.用法:先排序,在輸出第一個(gè)或者最后一個(gè),是求最值的常用方法,SQL語(yǔ)言中可以先將SC表中的Grade降序排序,然后輸出第一個(gè)求最高分。也請(qǐng)記住這種用法