Click here to Skip to main content
15,887,476 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a class, as defined below:
Python
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
Python
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.
Posted
Updated 11-Sep-18 19:22pm

1 solution

First, fix those syntax errors in your code, then try this:
newlist = sorted(oldlist, key=lambda x: x.cost)
Sorting HOW TO — Python 3.7.0 documentation[^]
 
Share this answer
 
v3
Comments
Stephane123wer 12-Sep-18 8:58am    
@Permalink when I run your code, I get the error

"AttributeError: 'tuple' object has no attribute 'cost'"
Peter Leow 12-Sep-18 10:07am    
How did u instantiate object of a class? Show you code.
Peter Leow 12-Sep-18 11:57am    
You are asking about the sorting, but showing some irrelevant code. Check this demo and figure out yourself http://rextester.com/YZNFBY8224

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900