gpt4 book ai didi

python - 如何从 python 集中删除自定义对象的实例?

转载 作者:行者123 更新时间:2023-11-28 22:17:07 25 4
gpt4 key购买 nike

我正在尝试使用 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

从牌组中移除死牌的正确方法是什么?为什么我的方法不起作用?

最佳答案

您的 Card 类需要两个新方法,以便集合和字典中的成员资格正常工作:

class Card:
...
def __hash__(self):
return hash(self.card)
def __eq__(self, other):
if isinstance(other, Card):
return self.card == other.card
return NotImplemented

这是因为集是用 hash tables 实现的,并且除非您定义如何对自定义类的实例进行散列和比较,否则基于 identity 的散列(CPython 中的内存位置)将用作默认值。使用 id 在这里提供了一个相当糟糕的默认值 - 两张具有相同号码/花色的牌不会被视为“相等”,并且不会识别 Deck 中的成员资格。

关于python - 如何从 python 集中删除自定义对象的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51615790/

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