gpt4 book ai didi

Python排序包含元组列表的类实例

转载 作者:行者123 更新时间:2023-12-01 08:41:28 24 4
gpt4 key购买 nike

这是《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

最佳答案

您缺少 Card 的定义 - 而且您正在创建 Card 的实例,而不是使用 tuplesort() 函数按元素对元组进行排序,当第一个元素发生绘制时使用下一个元素:

[ (0,1),(0,-2) ].sort() 

结果

[ (0,-2),(0,1) ] # because draw on (0,_)

对于你的Card类,python不知道如何对其进行排序,因此它使用id()函数(除非你告诉它如何对自己进行排序,见下文)。

您可以为调用 sort(...) 定义一个 key 或在您的函数上定义 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

另请参阅:

关于Python排序包含元组列表的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com