删除Python中重复的json结果

2024-06-22 21:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Flask中构建一个api,它获取博客文章列表,并通过标记变量进行过滤。当多个标记被发送到api时,它将返回任何带有这些标记之一的post。我的问题是,当使用多个标记时,它会返回一些重复的结果。所以当我使用这个:

@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,如果不存在该id,如何将其追加


Tags: 标记apiid列表tagtagsblogtech
2条回答

下面的方法应该有效

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)

相关问题 更多 >