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

Python中如何查找列表(List)内重复元素对应的所有下标索引

Python 获取列表中所有匹配元素的下标

Python 内置的 list.index() 方法只能返回第一个匹配元素的下标,要获取全部匹配的下标,可以用以下几种方案:

方案1:列表推导式(最推荐)

这是最简洁、可读性最高的写法,适合绝大多数场景:

lst = [1, 2, 3, 3, 4, 3, 5, 6]
indices = [i for i, value in enumerate(lst) if value == 3]
print(indices)
# 输出:[2, 3, 5]

方案2:filter 函数实现

如果偏好函数式写法,可以用filter组合lambda表达式实现:

indices = list(filter(lambda i: lst[i] == 3, range(len(lst))))

方案3:Numpy 实现(大数据量场景推荐)

如果是处理规模很大的数值列表,引入Numpy库可以获得更高的执行效率:

import numpy as np
arr = np.array(lst)
indices = np.where(arr == 3)[0].tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 15:12:01