You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python删除JSON中匹配黑名单分类的记录失败是什么原因?

问题根因

你的代码没有语法错误,del resource不生效是两个逻辑问题导致的:

  • 每次调用r.json()都会返回全新的列表对象,你循环遍历的是临时生成的列表,所有操作都不会作用到持久化的变量上
  • Python的for 元素 in 列表循环中,拿到的resource只是当前元素的临时绑定变量,del resource只会删除这个临时变量名,不会修改原列表,也不会把对应元素从原列表中移除
最优解决方案

推荐直接用列表推导式过滤生成符合要求的新列表,遍历过程中修改列表很容易因为长度变化出现异常,过滤的写法更简洁安全:

import requests

blacklisted_categories = [
    'Laptops'
]

# 发送请求拿到响应
r = requests.post("你的JSON接口地址")
# 先把返回的JSON列表存为变量,避免重复调用r.json()生成新对象
raw_product_list = r.json()

def trim_json(raw_list, category_blacklist):
    # 只保留分类不在黑名单内的记录
    return [item for item in raw_list if item["productCategory"] not in category_blacklist]

# 调用函数拿到处理后的结果
filtered_product_list = trim_json(raw_product_list, blacklisted_categories)

如果你确实需要在原列表上做删除操作,可以通过倒序遍历索引的方式实现:

def trim_json(raw_list, category_blacklist):
    # 倒序遍历索引,避免删除元素后索引错位
    for i in range(len(raw_list)-1, -1, -1):
        if raw_list[i]["productCategory"] in category_blacklist:
            del raw_list[i]
    return raw_list

内容的提问来源于stack exchange,提问作者Jonas Fagerlund

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 21:51:03