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

如何以列表方式迭代元组类型NumPy数组?解决迭代报错问题

修复nditer迭代含元组的object数组时的REFS_OK错误

你遇到的错误是因为数组元素属于引用类型(元组),np.nditer默认不允许处理引用类型,必须显式启用REFS_OK标志。下面提供两种修复方案:

方案1:使用nditer并启用REFS_OK标志

修改np.nditer的参数,添加flags=['refs_ok'],同时注意需要通过item.item()取出迭代器中的实际元组对象再解包:

import numpy as np

tmp = np.empty((), dtype=object)
tmp[()] = (0, 0)
arr = np.full(10, tmp, dtype=object)

# 启用refs_ok标志迭代引用类型元素
for item in np.nditer(arr, flags=['refs_ok']):
    a, b = item.item()
    print(a, b)

方案2:直接遍历数组(更简洁)

对于一维的object类型数组,直接遍历数组元素是更直观的方式,无需使用np.nditer:

import numpy as np

tmp = np.empty((), dtype=object)
tmp[()] = (0, 0)
arr = np.full(10, tmp, dtype=object)

# 直接遍历数组元素
for item in arr:
    a, b = item
    print(a, b)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:40:07