2013-05-12 90 views
0

我得到這個錯誤:我得到一個定義的錯誤,即使一切似乎是罰款

Traceback (most recent call last): 
    File "C:\Python27\botid.py", line 23, in <module> 
    fiList = {msg:submission.ups + len(coList)} 
NameError: name 'coList' is not defined 

此:

wbcWords = ['wbc', 'advice', 'prc','server'] 
while True: 
    subreddit = r.get_subreddit('MCPE') 
    for submission in subreddit.get_hot(limit=30): 
     op_text = submission.title.lower() 
     has_wbc = any(string in op_text for string in wbcWords) 
     # Test if it contains a WBC-related question 
     if submission.id not in already_done and has_wbc: 
      msg = '[WBC related thread](%s)' % submission.short_link 
      comments = submission.comments 
      for comment in comments: 
       coList = [comment.author.name] 
      fiList = {msg:submission.ups + len(coList)} 
      print fiList 

似乎沒什麼問題。所有的搜索結果最終都是拼寫錯誤,但我看起來很好(我希望)

回答

0

我想你應該嘗試:

coList = [] 
for comment in comments: 
    coList.append(comment.author.name) 

什麼,你還在想:

for comment in comments: 
    coList = [comment.author.name] 

對於每一個評論,此環復位colList到當前評論作者姓名的單個項目列表中,但我可以從你的評論中看到你已經理解了這一點。

與列表理解其他的評論是好得多海事組織,我個人也將使用:

colist = [comment.author.name for comment in comments] 

看起來比較清爽的一條線,你可以清晰地讀出的意圖是什麼,在作者列表註釋。

0

coList只在註釋非空時才被定義。如果註釋爲空,則coList將永遠不會被定義,因此會導致名稱錯誤。

它看起來像你在循環的每次迭代中重新定義coList,但它看起來可能是你真的想要追加到它?

+0

啊不,它應該只檢查一次,但這並不是什麼大問題。我試圖在for循環之前定義它,但我仍然得到相同的錯誤。 – user2374668 2013-05-12 10:33:28

2

我認爲最簡單的解決將是一個列表理解:

coList = [comment.author.name for comment in comments] 

這樣,如果評論是空的,你會得到一個空列表,否則作者姓名。另外,考慮到你輸入的內容,最好稱之爲authors_list

相關問題