【问题标题】:Print an array of object attributes from an array of objects从对象数组打印对象属性数组
【发布时间】:2020-03-23 15:31:24
【问题描述】:

我有一个带有一些属性的 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 有点陌生,看起来这应该比遍历数组更容易。

有吗?

【问题讨论】:

  • print([n.attribute for n in nodes])
  • 顺便说一句,@jordanm 评论中的语法称为 list comprehension,如果您想了解更多信息。

标签: python arrays class object


【解决方案1】:

这并不容易,因为在 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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-09
    • 2013-03-18
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多