1

在 NumPy 中,可以将整个数组段:作为索引范围的通配符进行分配。例如:

>>> (n, m) = (5,5)
>>> a = numpy.array([[0 for i in range(m)] for j in range(n)])
>>> a
array([[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]])

>>> for i in range(n):
...     a[i, :] = [1 for j in range(m)]
>>> a
array([[1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]])

但是,numpy.array仅保存数字数据。我需要一个可以容纳任意对象并且可以像 NumPy 数组一样寻址的数组类型。我应该使用什么?

编辑:我想要这个范围分配语法的完全灵活性,例如这也应该工作:

>>> a[:,1] = 42
>>> a
array([[ 1, 42,  1,  1,  1],
       [ 1, 42,  1,  1,  1],
       [ 1, 42,  1,  1,  1],
       [ 1, 42,  1,  1,  1],
       [ 1, 42,  1,  1,  1]])
4

2 回答 2

1

如果 numpy 不能满足您的需求,标准 Python 列表将:

>>> (n, m) = (5,5)
>>> 
>>> class Something:
...     def __repr__(self):
...         return("Something()")
... 
>>> class SomethingElse:
...     def __repr__(self):
...         return("SomethingElse()")
... 
>>> a = [[Something() for i in range(m)] for j in range(n)]
>>> 
>>> for i in range(n):
...     a[i] = [SomethingElse() for j in range(m)] #Use a[i][:] if you want to modify the sublist, not replace it.
... 
>>> a
[[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()],
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()],
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()],
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()],
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()]]
于 2012-05-07T16:59:34.853 回答
1

也许我在这里遗漏了一些东西,但 numpy 实际上确实保存了对象和数字。

In [1]: import numpy

In [2]: complex = {'field' : 'attribute'}

In [3]: class ReallyComplex(dict):
   ...:     pass
   ...: 

In [4]: a = numpy.array([complex,ReallyComplex(),0,'this is a string'])

In [5]: a
Out[5]: array([{'field': 'attribute'}, {}, 0, this is a string], dtype=object)
In [6]: subsection = a[2:]

In [7]: subsection
Out[7]: array([0, this is a string], dtype=object)

当您将复杂的对象放入一个 numpy 数组时,dtype会变成object. 您可以像使用普通 numpy 数组一样访问数组的成员和切片。我不熟悉序列化,但您可能会在该领域遇到缺点。

如果您确信 numpys 不是采用标准 Python 列表的方法,那么标准 Python 列表是维护对象集合的好方法,您也可以将 Python 列表切片为与 numpy 数组非常相似。

 std_list = ['this is a string', 0, {'field' : 'attribute'}]
 std_list[2:]
于 2012-05-07T16:54:32.783 回答