自定义类和sort()的问题

时间:2017-03-10 09:23:11

标签: python sorting

我做了一个习惯班作为练习,一副纸牌。我有一个可以使用random.shuffle()函数对其进行随机播放的函数,但我似乎无法使sort()正常工作,我知道我可以重建该套牌,但这并不是如果我在排序之前从卡座上取下了卡片,我就会工作。 sort()sorted()是否需要定义的__lt__以上?

import random

class Card:
    """ Represents a card using a suit and a rank
    suits are Clubs, Diamonds, Hearts, Spades represented by 0, 1, 2, 3
    the ranks are 1 to 13 for Ace, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King"""

    def __init__(self, rank=2, suit=1):
        self.rank = rank
        self.suit = suit

    suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
    rank_names = [None, 'Ace', '1', '2', '3', '4', '5', '6',
                 '7', '8', '9', '10', 'Jack', 'Queen', 'King']

    def __str__(self):
        return '%s of %s' %(Card.rank_names[self.rank], 
                            Card.suit_names[self.suit])

    def __lt__(self, other):
        return self.suit, self.rank < other.suit, other.rank

class Deck:
    """ Representing a deck of cards, containing one of each card """

    def __init__(self):
        self.new_deck()

    def new_deck(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1, 14):
                card = Card(rank, suit)
                self.cards.append(card)

    def __str__(self):
        res = []
        for card in self.cards:
            res.append(str(card))
        return '\n'.join(res)

    def pop_card(self):
        return self.cards.pop()

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

    def shuffle(self):
        random.shuffle(self.cards)

    def sort(self):
        self.cards.sort()


deck = Deck()
deck.shuffle()
deck.sort()
print(deck)

Python将随机打印,而deck.sort()只是不起作用

1 个答案:

答案 0 :(得分:3)

您的__lt__方法未返回bool,请尝试以下操作:

def __lt__(self, other):
    return (self.suit, self.rank) < (other.suit, other.rank)

tuple中的元素顺序如果不能提供你想要的顺序,可能会被交换:

def __lt__(self, other):
    return (self.rank, self.suit) < (other.rank, other.suit)