我正在尝试对元组列表进行排序。每个元组代表一个网格 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))
首先,我在将包含所有节点的网格列表放入类中时遇到问题,其次我收到错误:
TypeError:'<'实例之间不支持'getSortedKey' and 'getSortedKey'
我是朝着正确的方向前进,还是有一种简单的方法可以实现这一目标。
我可以通过编写自己的排序函数(冒泡排序)来实现我想要的,但它太慢了。我的下一步是编写一个快速排序,但在我的特定场景中我正在努力排序,所以我认为使用 Python 自己的排序会好得多,但显然我已经碰壁了。
感激地收到任何帮助。我已经搜索过类似的答案,但似乎没有什么是我需要的(除非我误解了其他答案)