Python,如何对对象列表进行排序?[重复]
发布于 2021-01-29 15:01:05
这个问题已经在这里有了答案 :
如何根据对象的属性对对象列表进行排序? (8个答案)
1年前关闭。
我有一个看起来像这样的对象列表。
hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ]
Card(10,’H)在这里不是元组,而是对象。我知道如果列表中的每个项目都是元组形式的,如何对列表进行排序,就像这样,
hand = sorted(hand, key = lambda x: x[0])
但我不知道如何对对象列表进行排序。我想按第一个输入值(即Card()中的数字)对列表进行排序
我怎样才能做到这一点?
编辑:这是Card()的定义。
class Card(object):
RANKS = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
SUITS = ('C', 'D', 'H', 'S')
def __init__(self, rank=12, suit='S'):
if (rank in Card.RANKS):
self.rank = rank
else:
self.rank = 12
if (suit in Card.SUITS):
self.suit = suit.upper()
else:
self.suit = 'S'
def __str__(self):
if (self.rank == 14):
rank = 'A'
elif (self.rank == 13):
rank = 'K'
elif (self.rank == 12):
rank = 'Q'
elif (self.rank == 11):
rank = 'J'
else:
rank = str(self.rank)
return rank + self.suit
def __eq__(self, other):
return (self.rank == other.rank)
def __ne__(self, other):
return (self.rank != other.rank)
def __lt__(self, other):
return (self.rank < other.rank)
def __le__(self, other):
return (self.rank <= other.rank)
def __gt__(self, other):
return (self.rank > other.rank)
def __ge__(self, other):
return (self.rank >= other.rank)
关注者
0
被浏览
83
1 个回答