下面的代码如何覆盖排序功能?我知道你也可以使用__gt__
翻转操作符。我似乎无法理解它是如何排序传递的对象列表。它不仅仅为每个人返回真/假吗?
例如
accounts = [["paladin", "1", "1050"],
["archer", "21", "995"],
["recruit", "3", "995"]]
按exp排序,如果exp相同,则按id排序。输出应为:
sortAccounts(accounts) = ["paladin", "recruit", "archer"].
代码:
def sortAccounts(accounts):
res = [Account(*account) for account in accounts]
res.sort(reverse=True)
return list(map(str, res))
class Account(object):
def __init__(self, name, id, xp):
self.name = name
self.id = int(id)
self.xp = int(xp)
def __lt__(self, other):
return self.id > other.id if self.xp == other.xp else self.xp < other.xp
def __str__(self):
return self.name