【问题标题】:Confused about a function in Learn Python the Hard Way ex41?对 Learn Python the Hard Way ex41 中的函数感到困惑?
【发布时间】:2013-08-02 23:58:13
【问题描述】:

我在这个练习的另一部分卡住了。正在编码的程序允许你钻短语(它给你一段代码,你写出英文翻译),我对“转换”功能的工作原理感到困惑。完整代码:http://learnpythonthehardway.org/book/ex41.html

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in
                   random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        # fake class names
        for word in class_names:
            result = result.replace("%%%", word, 1)

        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)

        # fake parameter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

我很迷茫。 w.capitalize() 中的“w”是文件本身,还是只是指列表中的对象?我也不确定为什么.count() 函数在.sample() 的参数中(或者.sample() 的真正作用)。第一个for_loop的目的是什么?

感谢您提供的所有帮助 - 很抱歉出现这么多问题。

【问题讨论】:

  • 如果您不确定标准库中的函数是做什么的,只需look it up。 Python 有很好的文档。

标签: python for-loop random-sample function


【解决方案1】:

如果能帮到你,

class_names = [w.capitalize() for w in
            random.sample(WORDS, snippet.count("%%%"))]

等价于

class_names = []
for w in random.sample(WORDS, snippet.count("%%%")):
    class_names.append(w.capitalize())

.count() 将返回“%%%”在 sn-p 字符串中出现的次数,因此 random.sample 将从 WORDS 列表中选择 N 个元素的子集,其中 N 是“ %%%" 在 sn-p 字符串中。

【讨论】:

    【解决方案2】:

    w.capitalize().uppercase() 类似,但它只对第一个字符进行大写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      相关资源
      最近更新 更多