exercise 25 更多更多練習

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)

1、split()函
語法:str.split(str="",num=string.count(str))[n]

參數說明:
str:表示爲分隔符,默認爲空格,但是不能爲空('')。若字符串中沒有分隔符,則把整個字符串作爲列表的一個元素
num:表示分割次數。如果存在參數num,則僅分隔成 num+1 個子字符串,並且每一個子字符串可以賦給新的變量
[n]:表示選取第n個分片

注意:當使用空格作爲分隔符時,對於中間爲空的項會自動忽略

2、os.path.split()函數
語法:os.path.split('PATH')

參數說明:

1.PATH指一個文件的全路徑作爲參數:

2.如果給出的是一個目錄和文件名,則輸出路徑和文件名

3.如果給出的是一個目錄名,則輸出路徑和爲空文件名


3、

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1

參數說明:

(1)  cmp參數:cmp接受一個函數,拿整形舉例,形式爲:

def f(a,b):

     return a-b

如果排序的元素是其他類型的,如果a邏輯小於b,函數返回負數;a邏輯等於b,函數返回0;a邏輯大於b,函數返回正數就行了

(2)  key參數:key也是接受一個函數,不同的是,這個函數只接受一個元素,形式如下

def f(a):

     return len(a)

key接受的函數返回值,表示此元素的權值,sort將按照權值大小進行排序

(3) reverse參數:接受False 或者True 表示是否逆序


4、pop() 函數用於移除列表中的一個元素(默認最後一個元素),並且返回該元素的值。

list.pop(obj=list[-1])

5、可以使用from ex25 import *的方法導入ex25中的所有函數

6、使用Ctrl+d結束python解析器。


分析:

  • import導入ex25.py文件,不用.py的後綴,這樣你就可以使用這個module裏面的所有函數了。?????
  • 定義sentence變量。
  • ex25.break_words,使用ex25.py中方法。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章