Python, how to sort list of object?
本问题已经有最佳答案,请猛点这里访问。
我有一个这样的对象列表。
1 | hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ] |
卡片(10,'h)这里不是一个元组,而是一个对象。如果列表中的每一项都是元组的形式,我知道如何对该列表进行排序,
1 | hand = sorted(hand, key = lambda x: x[0]) |
但我不知道如何对对象列表进行排序。我想按第一个输入值对列表进行排序,这是卡()中的数字。
我该怎么做?
编辑:这是card()的定义。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 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) |
这个想法还是一样的。只是您将在类对象中查找特定的属性。
对于你的卡片课,你可以这样做:
1 | hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ] |
那你就可以了
1 | sorted_cards = sorted(hand, key=lambda x: x.rank) |
输出如下所示:
1 2 | >>> [card.number for card in sorted_cards] [2, 10, 12, 13, 14] |
这是面向对象的方法。至少,您应该指定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Card(object): def __init__(self, rank, suit): self.rank = rank self.suit = suit def __eq__(self, other): return self.rank == other.rank and self.suit == other.suit def __lt__(self, other): return self.rank < other.rank hand = [Card(10, 'H'), Card(2, 'h'), Card(12, 'h'), Card(13, 'h'), Card(14, 'h')] hand_order = [c.rank for c in hand] # [10, 2, 12, 13, 14] hand_sorted = sorted(hand) hand_sorted_order = [c.rank for c in hand_sorted] # [2, 10, 12, 13, 14] |
如果适用,最好将对象排序逻辑设置为类的属性,而不是将其合并到需要排序的每个实例中。这样你每次都可以打电话给