【发布时间】: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