【问题标题】:Array type with range assignment needed需要范围分配的数组类型
【发布时间】:2012-05-07 16:49:25
【问题描述】:

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

【问题讨论】:

  • 你只需要那个特定的案例,还是像这样的简单案例就足够了?在这种情况下,内置列表可以正常工作,您只需省略逗号。
  • @delnan 两者都不是。我也想将此语法用于更复杂的情况。

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


【解决方案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:]

【讨论】:

  • "numpy 实际上像保存数字一样保存对象。"我没有意识到这一点,因为我尝试过: >>> a[0,0] = None Traceback (last recent call last): File "", line 1, in TypeError: int() argument必须是字符串或数字,而不是 'NoneType' 我想这可以解决我的问题。
【解决方案2】:

如果 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()]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2023-01-31
    • 2012-10-13
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    相关资源
    最近更新 更多