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

Python中获取numpy数组元素1的索引转列表报错解决

解决np.where返回结果转列表的AttributeError问题

错误原因

np.where()针对一维数组返回的是包含一个ndarray的元组(格式为(索引数组,)),而非直接的ndarray对象。直接对元组调用tolist()方法,会触发AttributeError: 'tuple' object has no attribute 'tolist'。

修复后的代码

提取元组中的第一个元素(存储索引的ndarray),再调用tolist()即可:

import numpy as np

A=np.array([0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

# 提取元组第一个元素后转列表
B = np.where(A == 1)[0].tolist()
print(B)

输出结果

[1, 2, 5, 7, 10, 11]

补充说明

np.where()的返回结构是为了兼容多维数组场景:处理二维数组时,会返回(行索引数组, 列索引数组)的元组。一维数组作为特殊情况,依然保持元组格式,因此必须通过索引[0]提取实际的索引数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:31:07