0

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:

  • Sort in descending by wins
  • If draw in wins sort descending by points
  • If draw in points sort ascending by name

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?

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.