for 루프 중 하나가 어떻게 Hard Way ex.41에서 Python을 배우는지 이해하는 데 어려움이 있습니다. http://learnpythonthehardway.org/book/ex41.html 아래는 수업의 코드입니다.어려운 방법으로 파이썬 배우기 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, 바라건대 당신은 내가 조금 더 명확하게 도움이 될 수 있습니다 : 이것은 좋은 디버거없이 디버깅 방법입니다. 그래서''@@@ ''이 3 번 나타납니다. 첫 번째 반복에서'param_count = random.randint (1,3)'코드의 다음 줄에서 임의의 정수'2 '를 얻을 수 있다고 가정 해 봅시다. 그런 다음 다음 줄의 코드'param_names.append (','.join (random.sample (WORDS, param_count))) '는 임의의 단어가'사과 '와'치즈 '라고 말할 수 있습니다. 'param_names = []'리스트에 추가 된 첫번째 항목은'[ ', apple, cheese']'일까요? 그 다음에는 3 번 반복이 목록에 추가됩니다. 유감스럽게도이 코드가 전체 코드에서 어떻게 작동하는지 확신하지 못했습니다. –
이전 주석에서 코드의 한 섹션을 제대로 끝내지 않았습니다. 나는 param_names.append (','.join (random.sample (WORDS, param_count)))'의 끝에 백틱을 두지 않았다. 실수로 하나의 qoute를 실수로 넣었고 코드 섹션을 제대로 끝내지 않았다. –
그래, 네가 말한 건 모두 옳은 것 같아. 'param_names []'리스트가 빌드되면'snippet'의 모든 "@@@"인스턴스는'param_names []'의 이름으로 대체됩니다. 코드를 이해하는 데 도움이 필요하면 알려주십시오. –