如何基于评论数合并并排序JSON格式的帖子与评论对象?
解决方案
直接用Python原生数据结构就能搞定,步骤如下:
1. 统计各帖子的评论数量
先遍历评论列表,用字典记录每个postId对应的评论数:
# 假设comments_json是你的评论数据,posts_json是帖子数据 comment_count = {} for comment in comments_json: post_id = comment['postId'] # 存在则计数+1,不存在初始化为1 comment_count[post_id] = comment_count.get(post_id, 0) + 1
2. 给帖子添加评论数字段
遍历帖子列表,把对应评论数(无评论则设为0)合并到帖子对象中:
for post in posts_json: post_id = post['id'] post['comment_count'] = comment_count.get(post_id, 0)
3. 按评论数降序排序
用Python的sorted函数指定排序规则,实现从多到少排序:
# 若评论数相同,可额外加排序条件比如帖子id,这里只按评论数倒序 sorted_posts = sorted(posts_json, key=lambda x: x['comment_count'], reverse=True)
完整示例代码
# 模拟测试数据 posts_json = [ {"id": 1, "author": "张三", "content": "第一篇帖子"}, {"id": 2, "author": "李四", "content": "第二篇帖子"}, {"id": 3, "author": "王五", "content": "第三篇帖子"} ] comments_json = [ {"postId": 1, "author": "赵六", "content": "评论1"}, {"postId": 1, "author": "孙七", "content": "评论2"}, {"postId": 2, "author": "周八", "content": "评论3"} ] # 统计评论数 comment_count = {} for comment in comments_json: post_id = comment['postId'] comment_count[post_id] = comment_count.get(post_id, 0) + 1 # 合并评论数到帖子 for post in posts_json: post['comment_count'] = comment_count.get(post['id'], 0) # 按评论数排序 sorted_posts = sorted(posts_json, key=lambda x: x['comment_count'], reverse=True) # 输出结果示例 for post in sorted_posts: print(f"帖子ID:{post['id']}, 作者:{post['author']}, 评论数:{post['comment_count']}")
这套逻辑纯用Python原生实现,不需要依赖Django ORM,直接在视图里执行就能完成合并、统计和排序的需求。
内容的提问来源于stack exchange,提问作者user18489452
相关产品推荐
相关产品推荐

