如果我想要.sort()来处理我的类列表,我的__lt__代码应该怎么样?

时间:2015-02-23 17:12:36

标签: python python-3.x

我创建了一个卡片组,每个玩家都被分配了一只手。我希望玩家能够先用最低的值排列他们的牌,然后打印出这手牌。我想这可以用.sort()完成,但是atm我收到了一条消息

TypeError: unorderable types: NumberedCard() < NumberedCard()  

我从网上得到一个提示,如果我定义.sort()是如何通过正确的def __lt__(self, other):那么我就不会遇到这个问题。所以帮助程序员搞清楚这一点。每张卡都由价值和套装定义。

我的代码如下所示:

import random

suitlist=["Hearts","Spades","Clubs","Diamonds"]

class NumberedCard():
    def __init__(self,value,suit):
        self.value=value
        self.suit=suit

    def __str__(self):
        return '%s of %s' %(self.value,suitlist[self.suit])

class JackCard():
    def __init__(self,suit):
        self.suit=suit
        self.value=11

    def __str__(self):
        return 'Jack of %s' %(suitlist[self.suit])

class QueenCard():
    def __init__(self,suit):
        self.suit=suit
        self.value=12

    def __str__(self):
        return 'Queen of %s' %(suitlist[self.suit])

class KingCard():
    def __init__(self,suit):
        self.suit=suit
        self.value=13

    def __str__(self):
        return 'King of %s' %(suitlist[self.suit])

class AceCard():
    def __init__(self,suit):
        self.suit=suit
        self.value=14
    def __str__(self):
        return 'Ace of %s' %(suitlist[self.suit])

class StandardDeck():
    """A class that creates a deck of 52 different cards, that also gives options to do matching operations with them"""
    def __init__(self):
        self.deck = []
        for suit in range(4):
            for value in range(2,11):
                card = NumberedCard(value,suit)
                self.deck.append(card)
            self.deck.append(JackCard(suit))
            self.deck.append(QueenCard(suit))
            self.deck.append(KingCard(suit))
            self.deck.append(AceCard(suit))
            #for k in range(52):
            #    print(self.deck[k])

    def shuffle(self):
        """Shake n' bake with the cards."""
        random.shuffle(self.deck)

    def take_card(self):                        
        return self.deck.pop()

    def deal_cards(self, hand,num):                
        for i in range(num):
            hand.add_card(self.take_card())

class Hand:
    """A class to do the usual poker things during the game. Ie pick up cards, drop cards etc."""
    def __init__(self):
       self.hand = []

    def __str__(self):
        Handen=""
        for card in self.hand:
            Handen+=str(card) + "\n"
        return Handen

    def add_card(self,card):
        self.hand.append(card)


    def sort_cards(self):
        self.hand.sort()


####Testing the program
deck=StandardDeck()
deck.shuffle()
hand=Hand()
hand.add_card(deck.take_card())
hand.add_card(deck.take_card())
print(hand)
hand.sort_cards()  # <---- This is the part not working

那怎么做呢?它应该放在哪里?

2 个答案:

答案 0 :(得分:2)

挽救这种情况的最佳方法是创建一个class Card,其中包含value__lt____gt__以及__eq__定义的方法。然后通过让所有其他卡继承自该父类来扩散这些方法。

提出的方法可以简单到只计算value int的值,而python知道如何自己做。

这样的事情:

>>> class Card(object):
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        if other.value > self.value:
            return True
        return False

>>> class Ace(Card):
    def __init__(self, value):
        super().__init__(value)

>>> class NumCard(Card):
    def __init(self, value):
        super().__init__(value)

>>> jack = Ace(12)
>>> n = NumCard(7)
>>> jack > n
True
>>> n > jack
False

答案 1 :(得分:0)

如果你只想在self.hand中对列表进行排序,为什么不直接使用key参数进行排序来创建一个函数来返回值以进行排序?

self.hand.sort(key=lambda x: x.value)

This link should provide some info on sorting techniques