排序引用对象的元组

2024-04-26 06:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对元组列表进行排序。每个元组表示一个网格x和y值。我想根据它们所表示的网格对象属性对元组进行排序。你知道吗

例如:

我的网格y * x elements,其中每个元素都有一个名为node的对象。每个节点都有一个名为globalGoal的属性。你知道吗

list a = [(1, 2), (2, 4)]

(1, 2) reference grid[1][2]

grid[1][2] = node

node.globalGoal = (int) value is the value I wish to sort

if (1, 2) represents the globalGoal value of 75 and
   (2, 4) represents the globalGoal value of 45 then
I want my list ordered as
[(2, 4), (1, 2)]

我从其他stackoverflow答案中收集的测试代码是:

class getSortedKey:
  global grid

  def __init__(self, node):
    self.node = grid[node[0]][node[1]].globalGoal

  def __cmp__(self, othernode):
    return(cmp(self.node, othernode))

a = [(1, 2), (2, 4)]
a.sort(key=lambda b: getSortedKey(b))

首先,我在获取包含类中所有节点的网格列表时遇到问题,其次,我得到错误:

类型错误:'<'的实例之间不支持'getSortedKey' and 'getSortedKey'

我是朝着正确的方向走,还是有一个简单的方法来实现这一点。你知道吗

我可以通过编写自己的排序函数(冒泡排序)来实现我想要的,但是它太慢了。我的下一步将是编写一个快速排序,但我在我的特定场景中正在努力排序,所以我认为使用Pythons自己的排序会更好,但显然我遇到了麻烦。你知道吗

感谢您的帮助。我寻找过类似的答案,但似乎没有什么是我需要的(除非我误解了其他答案)


Tags: the对象答案selfnode网格列表属性