2011-11-25 35 views
2

按照我的方式工作學習Python困難之路ex.25,而我無法將我的頭圍繞在某個東西上。這裏的腳本:爲什麼需要定義一些參數,而其他的不是? (Learn Python the Hard Way,ex。25)

def break_words(stuff): 
    """this function will break waords up 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 ones.""" 
    words = sort_sentence(sentence) 
    print_first_word(words) 
    print_last_word(words) 

運行腳本時,break_words會用我創造的任何說法,如果我用命令break_words(* *)。所以,我可以輸入

sentence = "My balogna has a first name, it's O-S-C-A-R" 

,然後運行break_words(句),並與解析「'我 'balogna' '有'(...)結束。

但是,其他功能(如sort_words )將只接受與名稱的函數「的話,」我必須鍵入 字= break_words(句子)

或東西sort_words工作。

我爲什麼可以傳遞任何參數在括號break_words,但只有實際歸因於的論點「sentence」和「words」專門用於sort_words,print_first_and_last等?我覺得在我繼續閱讀本書之前,這是我應該理解的基本內容,而且我無法理解它。

+0

這並不完全清楚你有什麼問題。請編輯您的問題,以包含一些示例程序以及您期望的輸出和實際獲得的輸出。 – SingleNegationElimination

回答

5

它是關於每個函數接受作爲其參數的值的類型。

break_words返回一個列表。 sort_words使用內置函數sorted(),該函數期望傳遞一個列表。這意味着您傳遞給sort_words的參數應該是一個列表。

也許下面的例子說明了這一點:

>>> sort_words(break_words(sentence)) 
['My', 'O-S-C-A-R', 'a', 'balogna', 'first', 'has', "it's", 'name,'] 

注意,蟒蛇默認爲是有幫助的,儘管這可能有時會造成混淆。所以如果你傳遞一個字符串到sorted(),它會把它當作一個字符列表。

>>> sorted("foo bar wibble") 
[' ', ' ', 'a', 'b', 'b', 'b', 'e', 'f', 'i', 'l', 'o', 'o', 'r', 'w'] 
>>> sorted(["foo", "bar", "wibble"]) 
['bar', 'foo', 'wibble'] 
+0

我想展示如何輸入一個文字列表(這樣他可以直接調用sort_words)也會很有啓發性。 – babbageclunk

+0

謝謝wilberforce。我認爲我們的編輯「在帖子中交叉」。我已經用sorted()直接演示了它 –

+0

不錯!我開始輸入一個答案,但是當你的答案出現時,它會和你的答案一樣。 :) – babbageclunk

相關問題