【问题标题】:'x' not in list while iterating over list迭代列表时“x”不在列表中
【发布时间】:2013-10-29 08:22:04
【问题描述】:

我试图做的是遍历一个 cmets 列表,删除已添加到名为 cText 的值的当前注释,如果 cText 超过 9000 个字符,则对同一函数进行递归调用并将其返回值添加到botComments。我还尝试将返回的botComments 列表从递归函数合并到最上面的botComments 列表和botComments + repliesToComments(comments, author),尽管我不知道我是否做对了。奇怪的是,它似乎也无法在列表中找到肯定有评论抛出我在下面粘贴的异常的评论。在我的 AP Comp-Sci 课程中,我的递归很糟糕,尽管我希望从任何可以修复我下面的代码的人那里了解我做错了什么。谢谢:)

这是我目前的例外情况:

Traceback (most recent call last):
  File "C:\Users\Josh\Desktop\bot.py", line 62, in <module>
    print(repliesToComments(submission.comments, submission.author.name))
  File "C:\Users\Josh\Desktop\bot.py", line 36, in repliesToComments
    botComments + repliesToComments(comments, author)
  File "C:\Users\Josh\Desktop\bot.py", line 39, in repliesToComments
    comments.remove(comment)
ValueError: list.remove(x): x not in list

这是我的代码:

def repliesToComments(comments, author):
    botComments = []
    multiReplies = False

    cText = "Here is a list of all the comments /u/" + author + ''' has submitted to top-level comments:
***
Original Comment | /u/''' + author + ''''s Reply
---------|---------
'''

    for comment in comments[:]:
        if (hasattr(comment, "replies")):
            for comment2 in comment.replies:
                if (hasattr(comment2, "author") and comment2.author.name == author):
                    oCommentLink = "[" + comment.body.replace("\n", "")[:50] + "](" + submission.permalink + "" + comment2.parent_id.replace("t1_", "") + ")..."
                    rCommentLink = "[" + comment2.body.replace("\n", "")[:50] + "](" + submission.permalink + "" + comment2.name.replace("t1_", "") + ")..."
                    if (len(cText) + len(oCommentLink + " | " + rCommentLink + "\n") > 9000): #Stop here to make sure we don't go over 10000 char limit!
                        multiReplies = True
                        cText += '''
***
[FAQ](http://pastebin.com/raw.php?i=wUGmE8X5) | Generated at ''' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " PST" + " | *This comment only shows a partial amount of OPs total replies due to character limit. The rest are shown in a reply to this comment.*"
                        botComments.append(cText)
                        botComments + repliesToComments(comments, author)
                        break
                    cText += oCommentLink + " | " + rCommentLink + "\n"
        comments.remove(comment)

    if (multiReplies == False):
        cText += '''
***
[FAQ](http://pastebin.com/raw.php?i=wUGmE8X5) | Generated at ''' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " PST"

    botComments.append(cText)
    return botComments

【问题讨论】:

    标签: python for-loop recursion python-3.x reddit


    【解决方案1】:

    您正在递归调用repliesToComments(),但使用完全相同的参数。这只会导致问题。

    您的递归调用正在从同一个列表中删除条目,当它返回时,这些条目仍然会消失。但是因为您遍历列表的副本,您的外部调用将不会被更新并尝试移除 cmets,内部递归调用已被移除

    也许您想在递归时调用 repliesToComments() 以获得不同的 cmets?我怀疑你的意思是用comment.replies 代替它?

    您的代码存在的另一个问题是您忽略递归调用的返回值:

    botComments + repliesToComments(comments, author)
    

    这将添加列表botComments 和递归调用的返回值,创建一个new 列表,然后您通过不将其分配给变量来将其放到地板上。您可能想使用:

    botComments += repliesToComments(comments, author)
    

    改为。

    【讨论】:

    • 我的意思是调用 repliesToComments() 并提供一个 cmets 列表不包括我已经迭代过的那些。
    • @Josh:调用完成后,您仍将遍历 rest。那是你的问题。
    • @Josh:假设你有一个列表 ['foo', 'bar', 'baz'] 并已删除 'foo',然后递归 ['bar', 'baz'],但递归调用也会删除 'bar',你的 outer 循环仍将处理'bar' 并尝试再次删除它
    • 啊,我明白你现在在说什么了。我将编辑我的代码以反映这些更改。感谢您的帮助@Martijn
    猜你喜欢
    • 1970-01-01
    • 2011-09-23
    • 2019-01-09
    • 2011-03-18
    • 2018-12-14
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多