我对以下陈述感到困惑
for sentence in snippet, phrase.
为什么""
背后有两个项目完整代码
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
答案 0 :(得分:4)
这只是一个双程循环。在第一次迭代中,sentence
设置为snippet
。在第二次迭代中,sentence
设置为phrase
。
这是一个简单的例子:
>>> for x in "a", "b":
... print(x)
...
a
b
>>>
答案 1 :(得分:3)
这是元组的另一种语法(语法糖),它是一个不可变的数据容器。你可以这样写:
for something in (1,2,3,4):
但是在这种情况下你可以省略括号,从而获得:
for something in 1,2,3,4:
这也是有效的语法。
for X in 1,2,3,4:
print X
打印以下内容:
1 2 3 4
答案 2 :(得分:0)
for循环只遍历可迭代集合中的每个项目。因此range(5)返回0到5之间所有项的可迭代集合.for循环允许您访问它。
>>> for x in range(5):
... print(x)
...
0
1
2
3
4
>>>