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

Python如何按嵌套列表首个字符串元素删除指定子列表

Python嵌套列表按首元素删除子列表的实现方法

方案1:列表推导式生成新列表(推荐,不修改原数据)

这种方法逻辑简单可读性高,不会改动原始列表,适合绝大多数场景:

def remove_by_first_value(origin_list, target_val):
    # 过滤所有首元素不等于目标值的子列表
    return [item for item in origin_list if item[0] != target_val]

测试用例:

# 原始数据
raw_data = [['NS1259', 163, 8.38, 268],
 ['NS6969', 88, 15.7, 620],
 ['NS4722', 155, 10.02, 343],
 ['NS3629', 150, 5.4, 530]]

# 调用函数删除首元素为NS6969的子列表
new_data = remove_by_first_value(raw_data, 'NS6969')
print(new_data)

运行输出:

[['NS1259', 163, 8.38, 268], ['NS4722', 155, 10.02, 343], ['NS3629', 150, 5.4, 530]]

方案2:原地修改原始列表

如果你需要直接修改原列表节省内存,要倒序遍历删除,避免正序删除时索引错位导致漏判:

def remove_by_first_value_inplace(origin_list, target_val):
    # 倒序遍历规避索引偏移问题
    for index in range(len(origin_list)-1, -1, -1):
        if origin_list[index][0] == target_val:
            del origin_list[index]
    return origin_list

注意事项

  • 两种方法都会删除所有首元素匹配的子列表,如果只需要删除第一个匹配项,可遍历列表找到第一个匹配索引后执行del origin_list[index]再break即可
  • 如果子列表可能为空,可以在判断条件里加非空校验,比如列表推导式改成[item for item in origin_list if item and item[0] != target_val],避免索引越界报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:45:05