为什么有些参数需要定义,而有些则不需要?(学习Python的艰难道路,例25)



努力学习第25期《学习Python》,我就是想不明白什么。脚本如下:

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(sentence)并以解析后的"'My' 'balogna' 'has'(…)"结束。

但是其他函数(如sort_words)只接受名称为"words"的函数。我必须打字Words = break_words(句子)

或者其他可以让sort_words工作的东西

为什么我可以在括号中传递break_words的任何参数,而只能传递给sort_words, print_first_and_last等实际归属于"sentence"one_answers"words"的参数?我觉得在我继续写这本书之前,我应该理解一些基本的东西,但我就是无法理解它。

这是关于每个函数接受作为其参数的值的类型。

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,']

请注意,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']

最新更新