【问题标题】:Why do some arguments need to be defined, and others not? (Learn Python the Hard Way, ex. 25)为什么有些参数需要定义,而有些则不需要? (Learn Python the Hard Way, ex. 25)
【发布时间】:2012-01-06 13:07:50
【问题描述】:

通过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(sentence)

或者让 sort_words 起作用的东西。

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

【问题讨论】:

  • 目前还不清楚您遇到了什么问题。请编辑您的问题以包含一些示例程序以及您期望的输出和实际获得的输出。

标签: python arguments declaration


【解决方案1】:

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

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

【讨论】:

  • 我认为展示如何输入文字列表(这样他可以直接调用 sort_words)也会很有启发性。
  • 感谢威尔伯福斯。我认为我们的编辑“在帖子中交叉”。我已经用 sorted() 直接演示过了
  • 不错!我已经开始输入一个答案,但是当你出现时,它的内容与你的相同。 :)
  • 谢谢,多米尼克。我现在正在努力做到这一点:我不能说我完全理解,但至少我知道我不知道什么,如果你知道我的意思的话。 :)
猜你喜欢
  • 2014-03-19
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多