拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 在Python中将用户定义的物件存盘在numpy阵列中

在Python中将用户定义的物件存盘在numpy阵列中

白鹭 - 2022-02-10 2127 0 0

如何将用户定义类的物件存盘在 numpy 阵列中?

我有这样的课:

class Node():
   
    def __init__(self):
        
        self.g = 0

import numpy as np

def main():
        node1 = Node()
        node2 = Node()

        my_array = np.empty( shape=(2, 3), dtype = 'Node' )
        my_array[0][1] = node1
        my_array[1][1] = node2

        print(my_array)

上面的代码抛出错误:TypeError: data type "Node" not understood.

uj5u.com热心网友回复:

解决方案1:

class Node():
   
    def __init__(self):
        
        self.g = 0

import numpy as np

def main():
        node1 = Node()
        node2 = Node()

        my_array = np.empty( shape=(2, 3), dtype = object)
        my_array[0][1] = node1
        my_array[1][1] = node2

        print(my_array)

解决方案2:

class Node1():
   
    def __init__(self,data):
        
        self.g = 0
        self.data= 1

import numpy as np

def main():
        node1 = Node1(1)
        node2 = Node1(2)

        my_array = np.empty( shape=(2, 3), dtype = np.dtype(Node1))
        my_array[0][1] = node1
        my_array[1][1] = node2

        print(my_array)

请浏览档案:https ://numpy.org/doc/stable/reference/arrays.dtypes.html

uj5u.com热心网友回复:

您的课程略有增强:

In [198]: class Node():
     ...:     def __init__(self,i):
     ...:         self.g = i
     ...:     def __repr__(self):
     ...:         return "<Node %s %s>"%(self.g, id(self))
     ...: 
     ...: node1 = Node(1)
     ...: node2 = Node(2)
     ...: 

实体:

In [199]: node1
Out[199]: <Node 1 140575230534224>
In [200]: node2
Out[200]: <Node 2 140575230535904>

包含实体的串列:

In [201]: alist = [node1, node2]
In [202]: alist
Out[202]: [<Node 1 140575230534224>, <Node 2 140575230535904>]

物件 dtype 阵列:

In [203]: arr = np.empty(3, dtype=object)
In [204]: arr
Out[204]: array([None, None, None], dtype=object)

像串列一样,它可以“保存”一个实体、一个数字或一个节点串列:

In [205]: arr[0]=node1
In [206]: arr[1]=123
In [207]: arr[2]=[node2, node1]
In [208]: arr
Out[208]: 
array([<Node 1 140575230534224>, 123,
       list([<Node 2 140575230535904>, <Node 1 140575230534224>])],
      dtype=object)

使用串列推导获取属性:

In [209]: [a.g for a in alist]
Out[209]: [1, 2]

或条件提取 - 从串列或阵列:

In [211]: [a.g for a in alist if isinstance(a,Node)]
Out[211]: [1, 2]
In [212]: [a.g for a in arr if isinstance(a,Node)]
Out[212]: [1]

阵列本身无法获取实体属性:

In [213]: arr.g
Traceback (most recent call last):
  File "<ipython-input-213-b925e810105d>", line 1, in <module>
    arr.g
AttributeError: 'numpy.ndarray' object has no attribute 'g'
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *