关于python:ValueError:list.remove(x):虽然传递了条件检查,但x不在列表中

ValueError: list.remove(x): x not in list although condition check is passed

我一直在跟踪如何像计算机科学家一样思考,我遇到了这个错误。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Card:
    suitList = ["Clubs","Diamonds","Hearts","Spades"]
    rankList = ["narf","Ace","2","3","4","5","6","7","8",
               "9","10","Jack","Queen","King"]
</p>

[cc lang="python"]def __init__(self, suit=0, rank=2):
    self.suit = suit
    self.rank = rank

def __str__(self):
    return (self.rankList[self.rank] +" of" +
            self.suitList[self.suit])

def __cmp__(self, other):
    if self.suit == 1: return 1
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    if self.rank > other.suit: return 1
    if self.rank < other.suit: return -1
    return 0

舱面:def init(自身):self.cards=[范围(4)内的西服(西服,军衔)范围(1,14)内的军衔]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def __str__(self):
    s =""
    for i in range(len(self.cards)):
        s = s +""*i + str(self.cards[i]) +"
"

    return s

def shuffle(self):
    import random
    nCards = len(self.cards)
    for i in range(nCards):
        j = random.randrange(i, nCards)
        self.cards[i], self.cards[j] = self.cards[j], self.cards[i]

def removeCard(self, card):
    if card in self.cards:
        self.cards.remove(card)
        return True
    else:
        return False

def popCard(self):
    return self.cards.pop()

def isEmpty(self):
    return (len(self.cards) == 0)

def deal(self, hands, nCards = 999):
    nHands = len(hands)
    for i in range(nCards):
        if self.isEmpty(): break
        card = self.popCard()
        hand = hands[i % nHands]
        hand.addCard(card)

班手(甲板):def init(self,name="):self.cards=[]self.name=姓名

1
2
3
4
5
6
7
8
9
10
11
def addCard(self, card):
    self.cards.append(card)

def __str__(self):
    s ="Hand" + self.name
    if self.isEmpty():
        return s +" is empty
"

    else:
        return s +" contains
"
+ Deck.__str__(self)

类别卡片名称:def init(自身):self.deck=甲板()self.deck.shuffle()。

老处女(手):def removematches(自我):计数=0originalcards=self.cards[:]对于原始卡中的卡:匹配=卡(3-card.suit,card.rank)如果在self.cards中匹配:自我卡。移除(卡)自我卡。移除(匹配)打印"手牌%s:%s与%s"%(self.name,card,match)计数=计数+1返回计数[/cc]

我得到的错误是:

1
2
3
4
5
6
Traceback (most recent call last):
File"<pyshell#3>", line 1, in <module>
hand.removeMatches()
File"C:\Users\Lin\projects\thinkcs\cardgame.py", line 89, in  removeMatches
self.cards.remove(match)
ValueError: list.remove(x): x not in list


我在你的__cmp__()函数中看到Card类的一个问题。-

1
2
3
4
5
6
7
def __cmp__(self, other):
    if self.suit == 1: return 1
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    if self.rank > other.suit: return 1 # Are you sure you want to compare rank with suit?
    if self.rank < other.suit: return -1 # Are you sure you want to compare rank with suit?
    return 0

您确定要将等级与套装进行比较吗?也许这就是导致问题的原因?