python - 从对象列表中删除对象

标签 python python-3.x list class

我基本上有 3 个类(class)。纸牌、牌组和播放器。 Deck 是卡片列表。我正在尝试从牌组中取出一张牌。但是我收到一个 ValueError 说该卡不在列表中。根据我的理解,它是并且我正在通过 removeCard 函数传递正确的对象。我不确定为什么会收到 ValueError。所以简而言之,问题是我需要从卡片列表中删除一个对象(卡片)。

我的问题是,当我尝试从牌组中取出卡片时,出现如下错误:

ValueError: list.remove(x): x not in list

这是我目前所拥有的:

卡片类:

import random

class Card(object):
    def __init__(self, number):
        self.number = number

Deck类(这里抛出错误,在removeCard函数中):

class Deck(object):
    def __init__(self):
        self.cards = []
        for i in range(11):
            for j in range(i):
                self.cards.append(Card(i))

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

    def removeCard(self, card):
        self.cards.remove(card)

    def showCards(self):
        return ''.join((str(x.number) + " ") for x in self.cards)

播放器类:

class Player(object):
    def __init__(self, name, hand):
        self.name = name
        self.hand = hand

主要函数:

def main():
    deck = Deck()
    handA = [Card(6), Card(5), Card(3)]
    handB = [Card(10), Card(6), Card(5)]
    playerA = Player("A", handA)
    playerB = Player("B", handB)

    print("There are " + str(len(deck.cards)) + " cards in the deck.")
    print("The deck contains " + deck.showCards())

    for i in handA:
        deck.removeCard(i)
    print("Now the deck contains " + deck.showCards())

main()

最佳答案

当您调用 list.remove 时,该函数会在列表中搜索项目,如果找到则将其删除。搜索时,它需要执行比较,将搜索项与其他所有列表项进行比较。

您正在传递一个要删除的对象。 用户定义的对象。在执行比较时,它们的行为方式与整数不同。

例如,object1 == object2,其中 object*Card 类的对象,默认情况下与它们唯一的 id 值。同时,您希望对卡号 进行比较,并相应地进行删除。

在你的类 (python-3.x) 中实现一个 __eq__ 方法 -

class Card(object):
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == other.number

现在,

len(deck.cards)
55

for i in handA:
    deck.removeCard(i)

len(deck.cards)
52

按预期工作。请注意,在 python-2.x 中,您将改为实现 __cmp__

关于python - 从对象列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48513729/

相关文章:

python - pandas DataFrame 中行之间的线性插值

python - 在 Python 中清除用户创建的变量

python - 将重复列表转换为具有相同键的组合列表

python - Python 中的填充列表

python - 导入变量初始化

c# - 如何连接 2 个列表

python - 我们可以从 py2exe 在 Python 中创建的可执行文件进行文件处理吗?

python - 在 Pandas Python 中形成组之前检查组是否包含元素

python - 在Python中使用seaborn在分布图上显示峰度、偏度等指标

python - 为什么我的按钮没有显示在 pygame 中?