我有一个字典,其中包含由包含5个变量的类组成的键。我想通过其中一个类变量对这本字典进行排序。
这是我目前拥有的
class Player:
def __init__(self,name,wins,losses,ties,winpercent):
self.__name = name
self.__wins = wins
self.__losses = losses
self.__ties = ties
self.__winpercent = winpercent
# mutators
def setname(self,name):
self.__name = name
def setwins(self,wins):
self.__wins = wins
def setlosses(self,losses):
self.__losses = losses
def setties(self,ties):
self.__ties = ties
def setwinpercent(self,winpercent):
self.__winpercent = winpercent
# accessors
def getname(self):
return self.__name
def getwins(self):
return self.__wins
def getlosses(self):
return self.__losses
def getties(self):
return self.__ties
def getwinpercent(self):
return self.__winpercent
def displayHighScores(self):
print("\n"," "*2,self.__name," "*(24-len(self.__name)),self.__wins)
def displayplayers(self):
print(self.__name)
我存储像这样的玩家:
def addplayer(players):
newName = input("\nEnter new Player name or 9 to quit: ")
wins = "0"
losses = "0"
ties = "0"
winpercent = "0"
if not newName:
print("\nNo name detected try again")
addplayer(players)
elif newName == '9':
print("\nReturning to Options menu")
else:
players[newName] = Player(newName,wins,losses,ties,winpercent)
saveData(players)
return players
最后,我正在制作一个排序好的分数列表。现在我可以像这样打印我的字典:
def printhiscores(players):
print("\n"," "*13,"HiScores")
print(" "*3,"Name"," "*20,"Wins")
if len(players) == 0:
print("\nNo current Players in memory.")
else:
for x in players.keys():
players[x].displayHighScores()
DisplayHighScores()是类对象的一部分。
我一直在阅读使用
进行字典排序OrderedDict(sorted(players.items(), key=itemgetter(1)))
但是返回编辑:TypeError:'<' “播放器”和“播放器”
的实例之间不受支持我想再次按照他们的win属性对玩家字典进行排序,然后将这个新订单打印到高分屏幕。任何帮助将不胜感激。如果我自己在这方面取得更多进展,我会发布。
答案 0 :(得分:0)
但是,Player
个实例不可订购,因为它们没有实施比较方法:
TypeError: '<' not supported between instances of 'Player' and 'Player'
如果您想按返回的值对它们进行排序,比如说, wins ,那么只需访问该信息而不是仅返回值:
OrderedDict(sorted(players.items(), key=lambda kv: kv[1].getwins()))
否则,请提供Player
课程rich comparison methods;用于确定何时应在另一个实例之前或之后对其进行排序的方法。您还需要一个equality test。只需实现对<
(低于)和相等的支持,然后使用@functools.total_ordering
decorator提供其余的支持:
from functools import total_ordering
@total_ordering
class Player:
def __lt__(self, other):
if not isinstance(other, Player):
return NotImplemented
return self.__wins < other.__wins
def __eq__(self, other):
if not isinstance(other, Player):
return NotImplemented
return self.__wins == other.__wins
以上使得两个Player
实例在胜利相等时相等,并按该属性对它们进行排序。您需要根据需要为您的应用程序调整此项。