【问题标题】:Python 3 with NumPy and object references带有 NumPy 和对象引用的 Python 3
【发布时间】:2011-11-19 09:28:55
【问题描述】:

我需要创建一个大型矩阵(数组)结构(3 轴),并且每个元素都应该存储对 Python 对象(myclass 实例)的引用。是否可以使用 numpy 创建这样的数组。我应该使用哪种数据类型来存储 Python 引用? numpy 的优点是支持不同层次的切片。另一种方法是创建一个嵌套(嵌套)列表,但它是一个繁琐的解决方案。

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    使用dtype=object 将 Python 对象存储在数组中。

    import numpy as np
    
    class Foo: pass
    
    arr=np.empty(2,dtype=object)
    arr[:]=[Foo(),Foo()]
    print(arr)
    # [<__main__.Foo instance at 0xb7827d0c>
    #  <__main__.Foo instance at 0xb748b5ac>]
    
    print(arr.dtype)
    # object
    

    【讨论】:

    • 如果你好奇,你可以检查一下 NumPy 只是将指针存储在 dtype 数组中的对象object:x = object(); a = np.array([x, x]); print (id(x), id(x)) == struct.unpack('2L',ctypes.string_at(a.ctypes.data, 8))(32 位 Python)。
    • @eryksun:您可以简单地将ctypes.string_at(a.ctypes.data, 8) 替换为更简单、更通用的a.tostring()
    • @eryksun: +1'd your cmets: ctypes.string_at() 确实是一个有趣的功能。 :)
    【解决方案2】:

    只需将object 作为 dtype,您就可以存储任何您想要的内容。

    import numpy
    
    print numpy.array([['a', (2, 2)], [1, 2+3j], [open, xrange(7)]], dtype=object)
    

    任何无法识别的类型都会以这种方式工作,因此您可能希望使用myclass 而不是objectobject 只是明确表示您将存储任意对象而无需任何 numpy 优化。请参阅the docs 了解更多信息。

    【讨论】:

      【解决方案3】:

      您不必做任何特别的事情:开箱即用:

      >>> import numpy
      >>> class TheClass(object):
      ...     pass
      ... 
      >>> numpy.array([TheClass(), TheClass()])
      
      array([<__main__.TheClass object at 0x10d435a50>,
             <__main__.TheClass object at 0x10d435a90>], dtype=object)
      

      NumPy 自动检测数组对象不是其标准标量类型之一(float、int 等),并通过自动将 dtype 设置为 object 来处理此问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 1970-01-01
        • 2017-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多