cuốn sách gpt4 ai đã làm

python - 为什么有些参数需要定义,有些则不需要? (艰难地学习 Python,例 25)

In lại Tác giả: Walker 123 更新时间:2023-11-28 22:03:50 26 4
mua khóa gpt4 Nike

我正在努力完成 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(sentence) 并以解析后的“'My' 'balogna' 'has' (...)”结束。

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

或者让 sort_words 起作用的东西。

为什么我可以在 break_words 的括号中传递任何参数,但只传递实际归因于“sentence”和“words”的参数,专门用于 sort_words、print_first_and_last 等?我觉得这是我在继续阅读本书之前应该了解的基本知识,但我无法理解它。

câu trả lời hay nhất

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

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

关于python - 为什么有些参数需要定义,有些则不需要? (艰难地学习 Python,例 25),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8272718/

26 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress