从对象列表中删除对象

Ayu*_*tel 2 python class list python-3.x

我基本上有3节课.卡片,甲板和播放器.甲板是一张卡片列表.我正试图从卡座上取下一张卡片.但是我得到一个ValueError,说卡不在列表中.从我的理解,它是,我通过该removeCard功能传递正确的对象.我不知道为什么我会得到一个ValueError.简而言之,问题是我需要从卡列表中删除一个对象(卡).

我的问题是,当我尝试从卡片中删除卡片时,我收到如下错误:

ValueError: list.remove(x): x not in list
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

Card 类:

import random

class Card(object):
    def __init__(self, number):
        self.number = number
Run Code Online (Sandbox Code Playgroud)

Deckclass(在函数中抛出错误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)
Run Code Online (Sandbox Code Playgroud)

Player 类:

class Player(object):
    def __init__(self, name, hand):
        self.name = name
        self.hand = hand
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 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
Run Code Online (Sandbox Code Playgroud)

现在,

len(deck.cards)
55

for i in handA:
    deck.removeCard(i)

len(deck.cards)
52
Run Code Online (Sandbox Code Playgroud)

按预期工作.请注意,在python-2.x中,您需要实现__cmp__.