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

Python中如何依据指定索引列表删除数组元素?

问题描述

给定数组arr:

arr = [
    [0.11, 2.6875],
    [0.11, 2.6875],
    [100, 200],
    [100, 200],
    [100, 200],
    [0.0033, 4.66677],
    [300, 400],
    [300, 400],
    [300, 400]
]

尝试用list.remove()删除元素未达预期,现有需删除元素的索引与元素元组列表:

[(1, [0.11, 2.6875]), (2, [100, 200]), (3, [100, 200]), (4, [100, 200]), (7, [300, 400]), (8, [300, 400])]

期望得到结果res:

res = [[0.11, 2.6875], [0.0033, 4.66677], [300, 400]]
解决方案

方法1:生成新列表(推荐)

先提取所有待删除的索引,再通过列表推导式保留不在删除索引中的元素,这种方法不会修改原数组,避免索引偏移问题:

# 提取待删除的索引集合
delete_indices = {idx for idx, _ in [(1, [0.11, 2.6875]), (2, [100, 200]), (3, [100, 200]), (4, [100, 200]), (7, [300, 400]), (8, [300, 400])]}
# 生成目标数组
res = [elem for idx, elem in enumerate(arr) if idx not in delete_indices]

方法2:反向修改原数组

如果必须修改原数组,需从后往前删除元素——正向删除会导致后续元素索引前移,引发删错或漏删问题:

# 提取待删除索引并按降序排序
delete_indices = sorted([idx for idx, _ in [(1, [0.11, 2.6875]), (2, [100, 200]), (3, [100, 200]), (4, [100, 200]), (7, [300, 400]), (8, [300, 400])]], reverse=True)
# 反向删除指定索引元素
for idx in delete_indices:
    del arr[idx]

执行后原数组arr将变为期望的结果。

为什么list.remove()不适用?

list.remove(x)只会删除第一个匹配x的元素,无法精准定位到指定索引的重复元素;且循环调用时,数组长度变化会导致后续元素索引偏移,最终无法达到预期删除效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:25:30