【发布时间】:2019-01-07 23:48:57
【问题描述】:
我正在玩一些 python 中的基本卡片/套牌操作。下面你可以看到我的 Card 类和 Deck 类。假设我知道有些牌已经死了,并且想将它们从牌组中移除。
import itertools
SUIT_LIST = ("h", "s", "d", "c")
NUMERAL_LIST = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A")
class Card:
def __init__(self, numeral, suit):
self.numeral = numeral
self.suit = suit
self.card = self.numeral, self.suit
def __repr__(self):
return self.numeral + self.suit
class Deck(set):
def __init__(self):
for numeral, suit in itertools.product(NUMERAL_LIST, SUIT_LIST):
self.add(Card(numeral, suit))
deck = Deck()
dead_card = Card('J','s')
deck.remove(dead_card)
引发以下错误:
Traceback (most recent call last):
File "<ipython-input-93-06af62ea1273>", line 23, in <module>
deck.remove(dead_card)
KeyError: Js
从我的牌组中移除死牌的正确方法是什么?为什么我这样做的方式不起作用?
【问题讨论】:
-
它不像你那样工作,因为你没有完成属于
set的项目的实现。 -
为什么不将卡片存储为字符串或元组?
标签: python python-3.x set