从对象数组中打印对象属性数组

时间:2020-03-23 15:31:24

标签: python arrays class object

我有一个带有某些属性的Node类

然后我有一个Node对象数组

nodes = [
    Node(some attributes),
    Node(some attributes),
    Node(some attributes),
]

我想做这样的事情

for i, node in enumerate(nodes):
    arr[i] = node.attribute

print(arr)

通过键入类似的内容

print(nodes.attribute)

print([nodes].attribute)

print(nodes[*].attribute)

然后让它返回类似

的内容
print(nodes) 

但具有特定的属性,而不是返回对象

我是python的新手,看来这比遍历数组更容易。

在吗?

1 个答案:

答案 0 :(得分:2)

并不是那么容易,因为在python中,方括号定义了列表,而不是数组。列表并不会强迫您在整个列表中使用相同类型的元素(在您的情况下为Node)。

您有一些选择:

遍历列表

您在问题中所做的同样的事情。

attributes = []
for node in nodes:
     attributes.append(node.attr)

列表理解

前一种的更多pythonic语法。

attributes = [node.attr for node in nodes]

在此列表上映射功能

这需要您定义一个函数,该函数接收节点并返回该节点的属性。

def get_attr(node)
    return node.attr

# or alternatively:
get_attr = lambda node: node.attr

attributes = map(getattr, nodes)

矢量化此函数并将数组作为参数传递

这可能是最接近您要执行的操作。它需要两件事:将前一个函数向量化并将nodes转换为数组。

import numpy as np
get_attr_vec = np.vectorize(get_attr)
nodes = np.array(nodes)

attributes = get_attr_vec(nodes)

要重现此示例,您需要首先定义节点列表:

class Node:
    def __init__(self, a):
        self.attr = a

n1 = Node(1)
n2 = Node(2)
n3 = Node(3)

nodes = [n1, n2, n3]

您还可以使用内置函数getattr代替点语法。

# These two are the same thing:
a = node.attr
a = getattr(node, 'attr')