2013-08-31 71 views
2

我無法理解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" 

回答

3

snippet.count("@@@")返回"@@@"出現在snippet的次數。

如果"@@@"出現6次,然後從0 for循環迭代至6

+0

感謝@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個迭代將被追加到列表中?最高法院,不知道如何在整個代碼 –

+0

如何工作請注意,我沒有在上一條評論中正確地結束一段代碼。 'param_names.append(','.join(random.sample(WORDS,param_count)))'''我錯誤地把一個qoute誤輸錯了,沒有正確地結束代碼部分 –

+0

是的,你所說的一切似乎都是正確的。一旦構建了'param_names []'列表,'snippet'中的所有''@@@'''實例將被替換爲'param_names []'中的名稱。讓我知道你是否需要更多幫助來理解代碼。 –

0

「嘗試除」塊中運行的程序,直到用戶點擊^ D.

「雖然真」循環內「try」將PHRASES dictonary中的密鑰列表存儲到片段中。密鑰的順序每次都不同(因爲洗牌方法)。 「for循環」裏面的「While循環」是通過每個片段並調用該片段的鍵和值的轉換方法。

所有「轉換方法」都會將該鍵和值的%%%,***和@@@替換爲url單詞列表中的一個隨機單詞,並返回一個列表(結果)由兩個字符串:一個由鍵構成,另一個由該值構成。

然後程序打印其中一個字符串作爲問題,然後獲取用戶輸入(使用raw_input(「>」)),但不管用戶輸入什麼,它都會打印另一個返回的字符串作爲答案。

在convert函數中,我們有三個不同的列表:class_names,other_names和param_names。 爲了製作class_names,程序會計算%%% isnide的數量(或值,但是它們的%%%數量相同)。 class_names將是%%%計數大小的單詞的隨機列表。

other_names是一個隨機的單詞列表。多少字?在密鑰中找到的***的數量(或值,無論哪一個,因爲它們在任何一對中都是相同的)

param_names是字符串列表中的@@@找到。每個字符串由一個,兩個或三個不同的單詞組成,分開,。

'result'是一個字符串。該程序遍歷三個列表(class_names,param_names和other_names),並將結果字符串中的某些內容替換爲已爲其準備好的內容。然後將其附加到結果列表中。 (用於片段,短語:)循環中的句子運行兩次,因爲「片段」和「短語」是兩個不同的字符串。所以,'結果'字符串正在進行兩次(一個用於問題1的答案)。

我把這個計劃的一個組成部分,以一個較小的子計劃,闡明如何從隨機單詞在URL中具有一定規模的列表中創建:

https://github.com/MahshidZ/python-recepies/blob/master/random_word_set.py

最後,我建議把打印聲明你需要更好地理解代碼的地方。舉一個例子,爲了這個代碼,我打印了許多變量來確切地知道發生了什麼。這是調試沒有調試好辦法:(尋找我的代碼中的布爾變量DEBUG)

DEBUG = 1 
if DEBUG: 
    print "snippet: " , snippet 
    print "phrase: ", phrase 
    print "class names: ", class_names 
    print "other names: " , other_names 
    print "param names: ", param_names