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

如何快速获取NumPy数组中指定元素的索引?

解决方法

你的代码逻辑存在问题:np.all的where参数并非用于元素级的条件判断,且lambda x: x in [1,2]无法对NumPy数组做逐元素的成员校验——这里的x是数组切片而非单个元素,导致所有结果都返回True。

针对你的需求(获取无重复元素数组中指定元素的索引),以下是几种高效的向量化实现方案:

方案1:按原数组顺序获取目标元素索引

如果只需要提取所有目标元素在原数组中的索引(不要求和目标列表顺序一致),可以用np.isin生成布尔掩码,再通过np.where提取索引:

import numpy as np

a = np.array([1,3,5,2,4])
target = [4,2]

# 生成标记目标元素的布尔掩码
mask = np.isin(a, target)
# 提取掩码为True的索引
indices = np.where(mask)[0]
print(indices)
# 输出: array([3, 4])

方案2:按目标列表顺序返回索引

如果需要匹配目标列表[4,2]的顺序返回对应索引(即输出array([4, 3])),可以利用np.searchsorted结合排序实现二分查找,效率极高:

import numpy as np

a = np.array([1,3,5,2,4])
target = [4,2]

# 对原数组和索引排序
sorted_indices = np.argsort(a)
sorted_a = a[sorted_indices]
# 通过二分查找定位目标元素,再映射回原索引
indices = sorted_indices[np.searchsorted(sorted_a, target)]
print(indices)
# 输出: array([4, 3])

方案3:字典映射批量提取

利用元素不重复的特性,先构建元素到索引的字典,再批量获取目标元素的索引,代码简洁直观:

import numpy as np

a = np.array([1,3,5,2,4])
target = [4,2]

elem_to_idx = {elem: idx for idx, elem in enumerate(a)}
indices = np.array([elem_to_idx[elem] for elem in target])
print(indices)
# 输出: array([4, 3])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:30:29