Python,如何对对象列表进行排序?

11

我有一个看起来像这样的对象列表。

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)

3
你需要为该类实现一个__eq____gt____lt__方法,这样当你比较该类的实例时,可以设置你的比较逻辑。请注意不改变原意,使翻译通俗易懂。 - idjaw
“Card”的定义会有所帮助……在类中那些变量的名称是什么? - Ctznkane525
@Ctznkane525 我刚刚添加了定义。 - Eric Kim
你当前的类没有进行排序吗? - Stephen Rauch
x.rank 是你需要的...下面的内容...只需要知道那个属性名就可以回答了。 - Ctznkane525
@EricKim,我已经添加了idjaw建议的解决方案。 - jpp
2个回答

25

这个概念仍然是一样的。只是您将要查找类对象中的特定属性。

对于您的卡牌类,您可以这样做:

hand = [ Card(10, 'H'), Card(2,'h'), Card(12,'h'), Card(13, 'h'), Card(14, 'h') ]

那么你可以这样做

sorted_cards = sorted(hand, key=lambda x: x.rank)

输出结果大致如下:

>>> [card.number for card in sorted_cards]
[2, 10, 12, 13, 14]

12

这是面向对象的方法。至少,您应该为其指定__eq____lt__操作才能使其正常工作。然后只需使用sorted(hand)

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]

如果适用的话,将对象排序逻辑作为类的属性而不是纳入每个需要排序的实例中,这是一个很好的实践方法。这样你就可以每次仅仅调用 sorted(list_of_objects)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接