【问题标题】:Retrieving a threaded comment list recursively递归检索线程化评论列表
【发布时间】:2015-11-01 03:27:51
【问题描述】:

我正在尝试编写一个递归函数,该函数可以从 Reddit 提交中检索嵌套的 cmets。我正在使用 Python + PRAW

def _get_comments(comments, ret = []):
    for comment in comments:
        if len(comment._replies) > 0:
            return _get_comments(tail(comments), ret + [{
                #"body": comment.body,
                "id": comment.id,
                "author": str(comment.author),
                "replies": map(lambda replies: _get_comments(replies, []), [comment._replies])
                }])
        else:
            return ret + [{
                    #"body": comment.body,
                    "id": comment.id,
                    "author": str(comment.author)
                }]
    return ret

def tail(list):
    return list[1:len(list)]

我得到以下输出,它不完整并且有嵌套数组:

pprint(_get_comments(s.comments))
[{'author': 'wheremydirigiblesat',
  'id': u'ctuzo4x',
  'replies': [[{'author': 'rhascal',
                'id': u'ctvd6jw',
                'replies': [[{'author': 'xeltius', 'id': u'ctvx1vq'}]]}]]},
 {'author': 'DemiDualism',
  'id': u'ctv54qs',
  'replies': [[{'author': 'rhascal',
                'id': u'ctv5pm1',
                'replies': [[{'author': 'blakeb43', 'id': u'ctvdb9c'}]]}]]},
 {'author': 'Final7C', 'id': u'ctvao9j'}]

Submission 对象有一个comments 属性,它是Comment 对象的列表。每个Comment 对象都有一个_replies 属性,该属性是更多Comments 的列表。

我错过了什么?我尽了最大努力——递归很难。

【问题讨论】:

标签: python recursion functional-programming reddit praw


【解决方案1】:

您几乎正确地理解了它。问题是,当递归很简单时,您正试图使递归变得复杂。您不需要 tail() 函数以及内部的 map() 函数,因为您已经在遍历 cmets。

我在示例中重命名了您的函数,因为它实际上将 cmets 转换为 dicts。

让我们从简单的案例开始,想一想:“好吧,我想要一个函数,它能够将 cmets 列表转换为 dicts 列表”。只是简单的功能:

def comments_to_dicts(comments):
    results = []  # create list for results
    for comment in comments:  # iterate over comments
        item = {
            "id": comment.id,
            "author": comment.author,
        }  # create dict from comment

        results.append(item)  # add converted item to results 
    return results  # return all converted comments

现在您希望 dict 还包含转换为 dicts 的回复列表。而且你已经有了能够进行这种转换的函数,所以让我们使用它并将结果放入item['replies']

def comments_to_dicts(comments):
    results = []  # create list for results
    for comment in comments:  # iterate over comments
        item = {
            "id": comment.id,
            "author": comment.author,
        }  # create dict from comment

        if len(comment._replies) > 0:
            item["replies"] = comments_to_dicts(comment._replies)  # convert replies using the same function

        results.append(item)  # add converted item to results 
    return results  # return all converted comments

因为你修改了你调用的同一个函数,它会转换所有的回复,不管它们有多深。希望更清楚递归的工作原理。

【讨论】:

  • 非常感谢。与我做的过于复杂相比,这非常清楚!
猜你喜欢
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多