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

如何将np.where获取的数组索引转换并合并为一维列表?

实现np.where索引合并为一维列表的方法

当然可行啦!你遇到的问题是因为np.where()返回的是包含一维数组的元组,直接拼接元组肯定得不到想要的结果。下面给你几种简单易懂的实现方式:

方法1:用numpy数组合并后转列表

先从np.where()的返回值中取出数组部分,再用np.concatenate()合并两个数组,最后转成Python列表:

import numpy as np

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
# 取出元组中的数组元素
y = np.where(l == 10)[0]
p = np.where(l == 5)[0]

# 合并数组并转成列表
result = np.concatenate([y, p]).tolist()
print(result)  # 输出: [0, 3, 6, 10, 14, 5, 11, 13]

方法2:转列表后直接相加

这种方式更直观,先把每个索引数组转成Python列表,再利用列表的+操作符直接合并:

import numpy as np

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
y = np.where(l == 10)[0].tolist()
p = np.where(l == 5)[0].tolist()

result = y + p
print(result)  # 输出: [0, 3, 6, 10, 14, 5, 11, 13]

可选:合并后排序(如果需要)

如果你希望合并后的索引是按从小到大排序的,可以在合并后调用sorted():

# 基于方法1的排序
result_sorted = sorted(np.concatenate([y, p]).tolist())
# 或者基于方法2的排序
result_sorted = sorted(y + p)
print(result_sorted)  # 输出: [0, 3, 5, 6, 10, 11, 13, 14]

核心思路就是先把np.where()返回的元组里的数组提取出来,再根据需求选择合并方式,最终转成一维列表即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:21:56