2013-08-01 61 views
2

我被困在这个练习的另一部分。正在编码的程序允许您钻取短语(它给了你一段代码,你写出了英文翻译),我对“转换”功能的工作方式感到困惑。完整代码:http://learnpythonthehardway.org/book/ex41.html在学习Python困难之路ex41中对函数感到困惑?

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的目的是什么?

非常感谢您提供的任何帮助和帮助 - 我为难以回答的问题感到抱歉。

+1

如果您不确定标准库中的某个函数的作用,请[查看](http://docs.python.org/2/library/random.html#random.sample)。 Python有很棒的文档。 – voithos

回答

4

如果它可以帮助你,

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之间的()将在片段返回字符串 “%%%” 的occurence的数量,所以random.sample将从WORDS列表中选择N个元素的一个子集,其中N是代码段字符串中“%%%”的元素。