Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对引用对象的元组进行排序_Python_Sorting - Fatal编程技术网

Python 对引用对象的元组进行排序

Python 对引用对象的元组进行排序,python,sorting,Python,Sorting,我正在尝试对元组列表进行排序。每个元组表示一个网格x和y值。我想根据它们表示的网格对象属性对元组进行排序 例如: 我的y*x元素网格,其中每个元素都有一个名为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

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

例如:

我的
y*x元素网格
,其中每个元素都有一个名为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))
首先,我在将包含所有节点的网格列表放入类时遇到问题,其次,我得到错误:

类型错误:
'
我是朝着正确的方向走,还是有一个简单的方法来实现这一点

确实有一个更简单的方法

a.sort(key=lambda c: grid[c[0]][c[1]].globalGoal)

正确阅读
list.sort()
文档和/或以下内容会节省大量时间(并学到更多):我做了,有很多东西需要学习。很明显,我对一些对你来说很明显的事情理解错误。它们对我来说并不重要,因此我来到这里。你知道,我并不是天生就有用Python编写代码的能力——我通过阅读文档和在交互式shell中尝试一些东西来证实我的理解;)这对我不起作用,它没有回报。我打印(a)给出[(3,2),(4,3)],然后执行代码,打印(a)再次返回无。很明显,这里有些东西我没有领会。好的,我发现了我的问题-谢谢-这确实有效,我正试图做a=a.sort(),但显然失败了。@AndyP
list.sort()
确实返回
——就像所有在FWIW中修改内容的内置方法一样。很高兴能提供一些帮助——如果我的答案解决了您的问题,请随时接受;)我确实点击了向上箭头,但它说我没有足够的声誉?除非我以另一种方式接受它?我还勾选了绿色箭头,这可能是您想要的:)