需要范围分配的数组类型

时间:2012-05-07 16:49:25

标签: python multidimensional-array numpy python-3.x

在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]])

2 个答案:

答案 0 :(得分: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列表切片为与numpy数组非常相似。

 std_list = ['this is a string', 0, {'field' : 'attribute'}]
 std_list[2:]

答案 1 :(得分: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()]]