我被困在这个练习的另一部分。正在编码的程序允许你钻取短语(它给你一段代码,你写出英文翻译),我对“转换”功能如何工作感到困惑。完整代码: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的目的是什么?
感谢您提供任何帮助 - 对不起,我很抱歉。
答案 0 :(得分: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()将返回片段字符串中“%%%”的出现次数,因此random.sample将从WORDS列表中选择N个元素的子集,其中N是“%%”的元素片段字符串中的“%”。
答案 1 :(得分:1)
values = sIzracuni.getRange(startrow,startcol,rownum,colnum).getDisplayValues();
与w.capitalize()
相似,但是它只能捕获第一个字符。