3

我被困在这个练习的另一部分。正在编码的程序允许您钻取短语(它给您一段代码,您写出英文翻译),我对“转换”功能的工作原理感到困惑。完整代码: 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”是来自w.capitalize()文件本身,还是只是指列表中的对象?我也不确定为什么该.count()函数在参数中.sample()(或.sample()真正的作用)。第一个 for_loop 的目的是什么?

感谢您的任何帮助-对于一连串的问题,我深表歉意。

4

2 回答 2

5

如果能帮到你,

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() 将返回片段字符串中“%%%”的出现次数,因此 random.sample 将从 WORDS 列表中选择 N 个元素的子集,其中 N 是“%%%”中的元素片段字符串。

于 2013-08-01T21:21:49.283 回答
1

w.capitalize()是 like .uppercase(),但它只显示第一个字符。

于 2020-11-14T17:43:45.217 回答