我有一个多维对象数组。我想使用 nditer 迭代器对对象进行交互。 这是一个代码示例:
import numpy as np
class Test:
def __init__(self,a):
self.a = a
def get_a(self):
return self.a
b = np.empty((2,3),dtype = object)
t_00 = Test(0)
t_01 = Test(1)
t_11 = Test (11)
b[0,0] = t_00
b[0,1] = t_01
b[1,1] = t_11
for item in np.nditer(b,flags = ["refs_ok"]):
if item:
print item.get_a()
我希望“项目”包含我可以用来访问数据的对象引用。 但是我收到以下错误:AttributeError: 'numpy.ndarray' object has no attribute 'get_a' 我的问题是如何通过数组访问数组中的对象?
最佳答案
迭代的 array.flat 方法将起作用,并且可以确认它如您预期的那样起作用
for item in b.flat:
if item:
print item.get_a()
关于Python 2.6 numpy 交互数组对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8755636/