这是“ Think Python”书中的练习18.2。有一个名为Deck
的类,它创建一副纸牌作为元组[(0,1), (0, 2)...]
的列表。该类已定义内部函数shuffle()
和sort()
。 shuffle()
函数可以正常工作,但是当我尝试对卡片组进行排序时,我编写的功能sort()
不会返回已排序的卡片组。
我不知道为什么会这样。任何提示我在做什么错?
class Deck(object):
"""Represents deck of cards
attributes: list of cards
"""
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
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()
new_deck = Deck()
print '>>>>>>>>>>>>>>>>>>>>new deck:'
print new_deck
new_deck.shuffle()
print '>>>>>>>>>>>>>>>>>>>>shuffled deck:'
print new_deck
new_deck.sort()
print '>>>>>>>>>>>>>>>>>>>>sorted deck:'
print new_deck
答案 0 :(得分:1)
您缺少Card
的定义-您还正在创建Card
的实例,而不是使用tuple
。 sort()
函数按元组对元组进行排序,当第一个元组发生绘制时,使用下一个元素:
[ (0,1),(0,-2) ].sort()
结果
[ (0,-2),(0,1) ] # because draw on (0,_)
对于您的Card
类,python不知道如何对其进行排序,因此它使用id()
函数(除非您告诉它如何对其进行排序,请参见下文)。
您可以为调用key
定义一个sort(...)
,也可以在卡上定义Card.__lq__()
的方法,这样它就不会使用id()
对卡片进行排序时:
import random
class Card(object):
# fancier output
s = {0:"hearts",1:"diamonds",2:"clubs",3:"spades"}
r = {i:v for i,v in enumerate( [ "Ace","2","3","4","5","6","7","8",
"9","10","Jack","Queen","King"],1)}
def __init__(self, suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return "{} of {}".format(Card.r[self.rank],Card.s[self.suit])
def __repr__(self):
return str(self)
# UNCOMMENT to not need the sort-key() in Deck
# def __lt__(self,other):
# return (self.suit,self.rank) < (other.suit, other.rank)
class Deck(object):
# keep the rest of your code, fix this:
# or uncomment __lq__() in Cards (which would be the prefered
# way to do it) and leave your method as is
def sort(self):
# tell sort to sort based on what key
self.cards.sort(key = lambda x: (x.suit, x.rank))
new_deck = Deck()
print '# new deck:'
print new_deck
new_deck.shuffle()
print '# shuffled deck:'
print new_deck
new_deck.sort()
print '# sorted deck:'
print new_deck
输出(缩短):
# new deck:
Ace of hearts ... up to ... King of hearts
Ace of diamonds ... up to ... King of diamonds
Ace of clubs ... up to ... King of clubs
Ace of spades ... up to ... King of spades
# shuffled deck:
6 of hearts
7 of spades
# ... snipp the remaining mixed cards ...
2 of hearts
King of diamonds
# sorted deck:
Ace of hearts ... up to ... King of hearts
Ace of diamonds ... up to ... King of diamonds
Ace of clubs ... up to ... King of clubs
Ace of spades ... up to ... King of spades
另请参阅: