【问题标题】:Remove an object from a list of objects从对象列表中删除一个对象
【发布时间】:2018-07-08 21:13:46
【问题描述】:

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

我的问题是,当我尝试从牌组中取出一张牌时,我收到如下错误:

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

这是我目前所拥有的:

Card类:

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)

Player类:

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

main函数:

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()

【问题讨论】:

  • 您在标题中提出了一个特定问题,但在您的问题正文中,对您的问题的描述过于宽泛,并且您的代码转储量很大。不确定您的问题到底是什么?
  • 对不起,我是第一次发帖。我基本上有3节课。卡片、甲板和播放器。甲板是一张卡片列表。我正在尝试从牌组中取出一张牌。但是我收到一个 ValueError 说该卡不在列表中。据我了解,它是并且我通过 removeCard 函数传递了正确的对象。我不确定为什么会收到 ValueError。所以简而言之,问题是我需要从卡片列表中删除一个对象(卡片)。

标签: python python-3.x list class


【解决方案1】:

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

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

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

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

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__

【讨论】:

  • 你很棒。我真的很喜欢你的解释。感谢您抽出宝贵时间回答这个问题。
  • @AyushiPatel 不客气。我还稍微修正了您的问题,以便从一开始就更容易理解您的问题。感谢您的澄清,祝您工作顺利。
猜你喜欢
  • 2021-07-11
  • 2020-11-07
  • 2016-11-14
  • 2021-08-03
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多