簡體   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