我有一个带有一些属性的 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 有点陌生,看起来这应该比遍历数组更容易。
在吗?
最佳答案
这并不容易,因为在 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')
关于python - 从对象数组打印对象属性数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60816623/