Mykola Kikets
Mykola Kikets

Reputation: 171

Python - Sorting with saved sorting order

I am very basic in python and I faced a little problem, which I can`t see the solution for that:

I have a list of class Player which has:

class player:
    def __init__(self,name,wins,points):
        self.name = name
        self.wins = wins
        self.points = points

later after making a list with data i need to sort in specific order:

I tried next variant of solution (which failed):

players.sort(key=lambda x: x.name)
players.sort(key=lambda x: x.points)
players.reverse()
players.sort(key=lambda x: x.wins)
players.reverse()

but after this i had a little problem with order (while wins are equal)... For example:

I have next data:

list({name:"Artur", points:20, wins:1},
     {name:"Jan", points:25, wins:1},
     {name:"Karol", points:10, wins:0})

after sorting I need to have next order:

Jan
Artur
Karol

but that solution that i made sorts partly wrong:
Result:

Artur
Jan
Karol

Why partly? Before final reverse it has right order:

"Karol"
"Jan"   #\this group
"Artur" #/ is in right positions

So there is some solution for that? Or maybe I just "Can`t find a solution from Internet"-man?

Upvotes: 0

Views: 486

Answers (3)

Booboo
Booboo

Reputation: 44108

You should be able to do it with one sort and using a lambda function by returning a tuple:

players.sort(key=lambda x: (-x.wins, -x.points, x.name))

Note that negative values are used to effect sort by descending values.

Upvotes: 2

Mykola Kikets
Mykola Kikets

Reputation: 171

Ok, sorry for interrupting, but i finded the solution by myself...
That was simple changing the position of 1 line:

players.sort(key=lambda x: x.name)
players.reverse() #this one...
players.sort(key=lambda x: x.points)
players.sort(key=lambda x: x.wins)
players.reverse()

Again, sorry for interrupt...

Upvotes: 0

Coderxyz
Coderxyz

Reputation: 215

I'm not sure why you are using lambda for this, but you need to add conditions to find if two players have equal points, if those conditions match then run an additional sort, then have another conditional for the final sort. Right now you are just sorting everything with the last condition on your list. You'll likely have to use a forloop to check next value against current value in the class.

Upvotes: 0

Related Questions