从对象列表中删除对象

时间:2018-01-30 04:06:05

标签: python python-3.x list class

我基本上有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()

1 个答案:

答案 0 :(得分:5)

当您致电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__

相关问题