简体   繁体   中英

How to sort a list of object based on the object attributes?

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?

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, ie converting score to integer in the lambda function while sorting:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM