我尝试做的是迭代注释列表,删除已添加到名为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
答案 0 :(得分:4)
您以递归方式调用repliesToComments()
,但使用完全相同的参数。这只会导致问题。
您的递归调用是从同一列表中删除条目,当它返回时,这些条目仍将消失。但是因为你循环遍历列表的副本,你的外部调用将不会被更新并尝试删除内部递归调用已删除已经的注释。
也许你想在递归时给repliesToComments()
调用一组不同的注释?我怀疑你打算用comment.replies
来代替它?
您的代码遇到的另一个问题是您忽略递归调用的返回值:
botComments + repliesToComments(comments, author)
这会添加列表botComments
和递归调用的返回值,创建一个 new 列表,然后通过不将其分配给变量将其放到地板上。您可能想要使用:
botComments += repliesToComments(comments, author)
代替。