Home > front end >  How to sort a list of object based on the object attributes?
How to sort a list of object based on the object attributes?

Time:12-06

so I'm working on a small game project using Python where the Players can input their names, and at the end of the game, their scores will be saved along with their names into a list. But I'm having a problem with showing and printing the sorted list based on their scores (descending). I've made something like this :

'''

class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score
    
    def getName(self):
        return(self.name)
    def getScore(self):
        return(self.score)


list_player = []
print("=== INPUT PLAYER ===")
while True:
    name = input("Input name : ")
    score = input("Input score : ")

    list_player.append(Player(name, score))

    print("INPUT PLAYER AGAIN ? [Y/N] : ", end=' ')
    c = str(input())
    print()
    if c == "N" or c == "n":
        break

print()
for i in list_player: 
    print("Name : "   i.name, end=' ')
    print("Score : "   i.score)

nl = []
nl = sorted(list_player, key=lambda player: player.score)

for i in nl:
    print("Name : "   i.name, end=' ')
    print("Score : "   i.score)

'''

This is the result of the program when executed :

=== INPUT PLAYER ===
Input name : aaa    
Input score : 200
INPUT PLAYER AGAIN ? [Y/N] :  y

Input name : ccc
Input score : 500
INPUT PLAYER AGAIN ? [Y/N] :  y

Input name : ddd
Input score : 1000
INPUT PLAYER AGAIN ? [Y/N] :  n


Name : aaa Score : 200
Name : ccc Score : 500
Name : ddd Score : 1000
Name : ddd Score : 1000
Name : aaa Score : 200
Name : ccc Score : 500

Here's the image to see it more clearly : execution result

I've tried using the sort() and sorted() method, but the result is still wrong.

With Java language, I could use Collections.sort(list_player, Comparator.compare(Player::getScore)). Is there the same method in Python ?

CodePudding user response:

Because you have not converted string to number, change your score input part to convert the input score to integer, as it makes sense to have score as an integer:

 score = int(input("Input score : "))

Another solution can be, to simple typecast the value to integer while sorting, and not touch what you have in the list, i.e. converting score to integer in the lambda function while sorting:

nl = sorted(list_player, key=lambda player: int(player.score))

And the order i.e. ascending/descending can be manipulated by reverse parameter to sorted built-in

  • Related