Click here to Skip to main content
15,175,959 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Updated 11-Sep-18 20: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[^]
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

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