繁体   English   中英

如何根据 object 属性对 object 列表进行排序?

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

所以我正在使用 Python 开发一个小型游戏项目,玩家可以在其中输入他们的名字,在游戏结束时,他们的分数将与他们的名字一起保存到一个列表中。 但是我在根据分数(降序)显示和打印排序列表时遇到问题。 我做了这样的事情:

'''

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)

'''

这是程序执行时的结果:

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

这是图像以更清楚地看到它:执行结果

我试过使用 sort() 和 sorted() 方法,但结果仍然是错误的。

使用 Java 语言,我可以使用 Collections.sort(list_player, Comparator.compare(Player::getScore))。 Python中是否有相同的方法?

因为您尚未将字符串转换为数字,所以更改您的分数输入部分以将输入分数转换为 integer,因为将分数作为 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))

并且可以通过reverse参数来操作顺序,即升序/降序,以sorted内置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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