【问题标题】:Python - get maximum dictionary key based on key attributePython - 根据键属性获取最大字典键
【发布时间】:2018-03-21 13:53:58
【问题描述】:

我有一个Node类定义如下(为了简化,我只复制了相关代码):

class Node(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.neighbours = []

我还有一个字典,其中 Node 对象作为键,键节点的邻居列表作为每个键的值。

successorTable = {
    Node(0, 1): [Node(1, 0)],
    Node(1, 0): [Node(0, 1)],
    # and so on ...
}

现在我想做的是获取最大值为x的字典键(Node对象)和最大值为y的键

所以我基本上是想得到以下结果:

# maxXNode -> Node(1, 0)
# maxYNode -> Node(0, 1)

【问题讨论】:

  • 你的 Node 对象有__hash__ 特殊方法吗?否则,这将无法按您的意愿工作。
  • 为什么需要successorTable?这不是Node.neighbours 的用途吗?也就是说,任何时候你使用successorTable[x],你都可以直接说x.neighbors
  • 后继节点是节点在一个特定方向上的邻居。这就是为什么我需要successorTable,它是图形的属性,而不是节点的。但是,我会在无向图中使用 Node.neighbours
  • @jdehesa,你的回答给了我一个线索,虽然我不得不修改它。谢谢。这是修改后的版本:max_key_x = max(successorTable.keys(), key=lambda n: n.y).ymax_key_y = max(successorTable.keys(), key=lambda n: n.x).x

标签: python dictionary attributes key max


【解决方案1】:

你的问题

首先,对于你的问题,你可以这样做。

max_x = max(successorTable.keys(), key=lambda n: n.x)
max_y = max(successorTable.keys(), key=lambda n: n.y)

其他问题

然后说说你的代码。

我建议您在使用 Node 作为字典键时要小心,因为您没有定义 __hash____eq__ 方法。

d = {}
d[Node(0, 0)] = 0
d[Node(0, 0)] # raises a KeyError

默认情况下,一个对象通过其 id 进行散列和比较,因此具有相同坐标的两个节点不会散列到相同的值。你可能想像这样解决这个问题。

class Node(object):
    def __init__(self, x, y):
        self._x = x
        self._y = y
        self.neighbours = []

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

    def __hash__(self):
        return hash((self.x, self.y))

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

我们使用_x_yproperty 来强调这些属性在用于散列时不应更新。

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2020-07-26
    • 2012-01-09
    • 1970-01-01
    • 2021-09-13
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多