为什么需要定义一些参数,而其他参数不需要?(以艰难的方式学习Python,例如25)

Jea*_*ius 2 python arguments declaration

通过学习Python艰难的方式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)
Run Code Online (Sandbox Code Playgroud)

运行脚本时,如果我使用命令break_words(**),break_words将使用我创建的任何参数.所以我可以输入

sentence = "My balogna has a first name, it's O-S-C-A-R"
Run Code Online (Sandbox Code Playgroud)

然后运行break_words(句子)并最终得到一个解析的"'我'''balogna''有'(...).

但是其他函数(如sort_words)只接受名为"words"的函数.我必须输入words = break_words(句子)

或者sort_words工作的东西.

为什么我可以在break_words的括号中传递任何参数,但只传递实际归因于sort_words,print_first_and_last等的"sentence"和"words"的参数?在我继续阅读本书之前,我觉得这是我应该理解的基本内容,而我无法理解它.

Dom*_*nin 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,']
Run Code Online (Sandbox Code Playgroud)

请注意,python默认有用,即使这有时会令人困惑.因此,如果将字符串传递给sorted(),它会将其视为字符列表.

>>> sorted("foo bar wibble")
[' ', ' ', 'a', 'b', 'b', 'b', 'e', 'f', 'i', 'l', 'o', 'o', 'r', 'w']
>>> sorted(["foo", "bar", "wibble"])
['bar', 'foo', 'wibble']
Run Code Online (Sandbox Code Playgroud)