我無法理解for循環中的一個for循環是如何工作的。 http://learnpythonthehardway.org/book/ex41.html以下是本課程的代碼。學習Python困難之路Ex.41困惑於For循環
,我感到困惑的是for i in range(0, snippet.count("@@@")):
是它遍歷範圍爲0至片斷(其中有6段),以及添加的「@@@」伯爵的額外價值的循環?因此,對於代碼param_count = random.randint(1,3)
的下一行,將應用「@@@」的額外值?還是我離開!?
乾杯 達倫
import random
from urllib import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)" :
"class %%% has-a __init__ that takes self and *** parameters.",
"class %%%(object):\n\tdef ***(self, @@@)":
"class %%% has-a function named *** that takes self and @@@ parameters.",
"*** = %%%()":
"Set *** to an instance of class %%%.",
"***.***(@@@)":
"From *** get the *** function, and call it with parameters self, @@@.",
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
}
# do they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
# load up the words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())
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
# keep going until they hit CTRL-D
try:
while True:
snippets = PHRASES.keys()
random.shuffle(snippets)
for snippet in snippets:
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST:
question, answer = answer, question
print question
raw_input("> ")
print "ANSWER: %s\n\n" % answer
except EOFError:
print "\nBye"
感謝@Omar Abdeldayem,希望你可以幫我澄清遠一點。所以我們假設''@@@「'出現三次。在第一次迭代中,假設我從下一行代碼'param_count = random.randint(1,3)'得到隨機整數'2'。然後對於下一行代碼'param_names.append(','.join(random.sample(WORDS,param_count)))'可以說隨機單詞是'apple'和'cheese'。第一個添加到'param_names = []'列表中的項目是否是'[',apple,cheese']'?在那之後,3個迭代將被追加到列表中?最高法院,不知道如何在整個代碼 –
如何工作請注意,我沒有在上一條評論中正確地結束一段代碼。 'param_names.append(','.join(random.sample(WORDS,param_count)))'''我錯誤地把一個qoute誤輸錯了,沒有正確地結束代碼部分 –
是的,你所說的一切似乎都是正確的。一旦構建了'param_names []'列表,'snippet'中的所有''@@@'''實例將被替換爲'param_names []'中的名稱。讓我知道你是否需要更多幫助來理解代碼。 –