通常,可以将任意对象放入numpy数组:
class Foo(object):
pass
np.array([ Foo() ])
>>> array([<__main__.Foo object at 0x10d7c3610>], dtype=object)但是,实现__len__和__getitem__的对象似乎自动“解压缩”:
class Foo(object):
def __len__(self): return 3
def __getitem__(self, i): return i*11
np.array([ Foo() ])
>>> array([[0, 11, 22]])有什么方法可以阻止numpy以这种方式解压对象吗?我想要的是将一些对象放入一个numpy数组中,并将它们作为对象本身存储,而不需要进行解压缩。所以想要的行为是:
class Foo(object):
def __len__(self): return 3
def __getitem__(self, i): return i*11
np.array([ Foo() ])
>>> array([<__main__.Foo object at 0x10d7c3610>], dtype=object)现在,我理解了鸭子输入的想法意味着numpy应该打开任何看起来像列表的东西。但是,也许可以以某种方式标记类Foo,告诉numpy不要打开它?例如,ABC:
numpy.Nonenumerable.register(Foo)发布于 2014-03-10 00:44:41
x = numpy.empty(appropriate_shape, dtype=object)
x[:] = your_list_of_foos例如,对于1 Foo的一维数组,
x = numpy.empty([1], dtype=object)
x[:] = [Foo()]这样做的好处是可以处理您无法控制的类型,或者系统的其他部分可能希望被解压缩。例如,如果希望将2个列表视为一维列表数组,
x = numpy.empty([2], dtype=object)
x[:] = [[], []]发布于 2014-03-10 00:37:51
发布于 2014-03-10 00:39:12
也许把类似数组的对象封装在容器中?
class Bar():
def __init__(self):
self.foo = Foo()Np.array(律师())
https://stackoverflow.com/questions/22290204
复制相似问题