python - 在 Python 中删除重复的 json 结果
问题描述
我正在 Flask 中构建一个 api,它获取博客文章列表并由标签变量过滤。当多个标签被发送到 api 时,它会返回任何带有这些标签的帖子。我的问题是,当使用多个标签时,它会返回一些重复的结果。所以当我使用这个时:
@app.route('/api/posts')
def Posts():
tag_str = request.args.get("tags")
if tag_str == None:
return {"Error": "Tags parameter is required"}, 400
tags = tag_str.split(",")
data = []
for tag in tags:
blog = requests.get(f"https://hatchways.io/api/assessment/blog/posts?tag={tag}").json()
data += blog["posts"]
我回来了:
> "posts": [
{
"author": "Rylee Paul",
"authorId": 9,
"id": 1,
"likes": 960,
"popularity": 0.13,
"reads": 50361,
"tags": [
"tech",
"health"
]
},
{
"author": "Rylee Paul",
"authorId": 9,
"id": 1,
"likes": 960,
"popularity": 0.13,
"reads": 50361,
"tags": [
"tech",
"health"
]
},
{
"author": "Zackery Turner",
"authorId": 12,
"id": 2,
"likes": 469,
"popularity": 0.68,
"reads": 90406,
"tags": [
"startups",
"tech",
"history"
]
id 是一个唯一值,那么我该如何做一个 if 语句,它基本上检查该 id 是否已经存在于列表中,如果不存在则附加它?
解决方案
下面应该工作
posts = [
{
"author": "Rylee Paul",
"authorId": 9,
"id": 1,
"likes": 960,
"popularity": 0.13,
"reads": 50361,
"tags": [
"tech",
"health"
]
},
{
"author": "Rylee Paul",
"authorId": 9,
"id": 1,
"likes": 960,
"popularity": 0.13,
"reads": 50361,
"tags": [
"tech",
"health"
]
},
{
"author": "Zackery Turner",
"authorId": 12,
"id": 2,
"likes": 469,
"popularity": 0.68,
"reads": 90406,
"tags": [
"startups",
"tech",
"history"]
}
]
post_ids = set()
filtered_posts = []
for p in posts:
if p['id'] not in post_ids:
filtered_posts.append(p)
post_ids.add(p['id'])
print(filtered_posts)
推荐阅读
- javascript - JavaScript 输入参数用空格分隔
- sql-server - 子查询返回超过 1 个值 - SQL 错误
- docker - 无法使用 Jenkins CloudFoundryPlugin 将 docker 映像推送到 Cloud Foundry
- google-chrome-extension - 如何制作可在网站上自动启用 Flash 的扩展程序?
- node.js - 从节点客户端发送事件到 Laravel Echo 服务器
- python - 根据包含映射的文件将 COL A 的值替换为 COL B 的值
- python - 绘制比例轴标签单位
- typescript - 如何在打字稿中计算 SMS 消息段?
- python - 使用索引数组中的索引元组索引多维数组 - NumPy / Python
- android - Google play 上的新格式 Bundle 应用怎么样?