2013-05-12 23 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

相关问题