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

如何删除Python列表字典中的空值并生成新列表?

解决方法

你的原始代码存在两个核心问题:

  • res['Client'] 是一个列表,用 not in '' 判断完全不成立,列表不可能是单个空字符串的成员
  • 未处理 description 为空的情况,也没有清理 Client 列表内部的空值

下面是符合需求的实现代码:

result = []
for item in list_1:
    # 跳过description为空字符串的字典
    if item.get('description', '') == '':
        continue
    # 清理Client列表中的空字符串
    cleaned_clients = [client for client in item['Client'] if client != '']
    # 仅保留清理后Client列表非空的字典
    if cleaned_clients:
        # 创建字典副本,避免修改原始数据
        processed_item = item.copy()
        processed_item['Client'] = cleaned_clients
        result.append(processed_item)

代码说明:

  • 通过 item.get('description', '') == '' 判断描述字段是否为空,为空则直接跳过当前字典
  • 用列表推导式过滤 Client 列表内的空字符串,得到仅含有效内容的客户端列表
  • 只有当清理后的 Client 列表非空时,才将处理后的字典加入结果列表(若需保留Client为空的情况,可删除此判断)
  • 调用 item.copy() 创建字典副本,避免修改原始列表中的数据

如果允许直接修改原始数据(不推荐),可简化为:

result = []
for item in list_1:
    if item['description'] != '':
        item['Client'] = [c for c in item['Client'] if c != '']
        if item['Client']:
            result.append(item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:18:13