即使一切似乎都很好,我也会得到一个定义的错误

时间:2013-05-12 10:20:48

标签: python nameerror

我收到了这个错误:

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

对我来说似乎很好。所有搜索结果最终都是拼写错误,但我觉得很好(我希望)

3 个答案:

答案 0 :(得分:2)

我认为最简单的解决方案是列表理解:

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

这样,如果comments为空,则会得到一个空列表,否则为作者姓名。另外,根据您输入的内容,最好将其称为authors_list

答案 1 :(得分:0)

只有在注释非空时才会定义coList。如果comments为空,则永远不会定义coList,因此产生的名称错误。

看起来你在循环的每次迭代中都重新定义了coList,但看起来你真的想要追加它吗?

答案 2 :(得分: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]

看起来更清晰一行,你可以清楚地看到意图是什么,评论中的作者列表。