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

Python中定位数组元素1的索引并转换为列表报错求助

解决numpy数组查找值为1的索引时的AttributeError问题

错误原因

np.where()返回的是一个元组,其中包含对应维度上符合条件的索引数组。直接对元组调用tolist()方法会触发AttributeError,因为元组本身没有这个属性。

修正方案

需要先提取元组中的索引数组,再转换为列表,最后包裹成二维列表以匹配期望输出。以下是两种可行写法:

写法一:直接提取索引数组并转换

import numpy as np

A = np.array([[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0]])
# 取出元组中的第一个索引数组,转换为普通列表
index_list = np.where(A[0] == 1)[0].tolist()
# 包裹成二维列表
result = [index_list]
print(result)

写法二:遍历元组处理所有维度(适配多维数组场景)

import numpy as np

A = np.array([[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0]])
index_tuple = np.where(A[0] == 1)
# 遍历元组中的每个索引数组,转换为列表后组成二维列表
result = [arr.tolist() for arr in index_tuple]
print(result)

输出结果

两种写法的输出均为:

[[0, 2, 3, 5]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:22:04