按属性排序对象数组 [英] Sorting array of objects by attribute
本文介绍了按属性排序对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个课程,定义如下:
class 节点():
def _init_(self,xcoordinate = 无,ycoordinate = 无,h =无,g =无,成本=无):
self.xcoordinate = xcoordinate
self.ycoordinate = ycoordinate
self.h = h
self.g = g
self.cost = h + g
def _repr_(self):
return repr((self.xcoordinate,self.ycoordinate,self.h,self.g,self.cost))
然后我有一个Node对象数组。如何根据Node.cost排序此数组?(对象成本属性)。
我尝试过:
我尝试使用下面的行
已排序(possible_next_steps,key = lambda node:node [ 4 ])
但会抛出IndexError:元组索引超出范围错误。我非常感谢你的帮助,谢谢。
解决方案
首先,修复代码中的语法错误,然后试试这个:newlist = sorted( oldlist,key = lambda x:x.cost)
I have a class, as defined below:
class Node():
def _init_(self, xcoordinate= None, ycoordinate= None, h=None, g=None, cost=None):
self.xcoordinate = xcoordinate
self.ycoordinate = ycoordinate
self.h = h
self.g = g
self.cost = h + g
def _repr_(self):
return repr((self.xcoordinate, self.ycoordinate, self.h, self.g, self.cost))
I then have an array of Node objects. How do I sort this array based on the Node.cost?(the objects cost attribute).
What I have tried:
I have tried using the line below
sorted(possible_next_steps, key=lambda node: node[4])
but that throws an "IndexError: tuple index out of range" error. I would really appreciate your help, thanks.
解决方案
First, fix those syntax errors in your code, then try this:newlist = sorted(oldlist, key=lambda x: x.cost)
这篇关于按属性排序对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文