gpt4 book ai didi

Python--从列表中删除对象

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:37 25 4
gpt4 key购买 nike

我想做的是制作一副牌,然后将牌组中的特定牌移到玩家手中。我在创建牌组并将牌添加到玩家手上时没有遇到任何问题,但每当我尝试从牌组中取出牌时,它都会告诉我该牌一开始就不在牌组中,这是没有意义的。

这里是相关代码

class Card(object):

suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] #so zero returns nothing, an Ace is 1 and so forth

def __init__(self, suit, rank): #initial method, just defines suit and rank so you can find it later
self.suit = suit
self.rank = rank

def getRank(self): #returns the rank of the card as an integer
return self.rank

def getSuit(self): #returns suit as an integer
return self.suit

def __str__(self):
return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit])

class Deck(object):

def __init__(self): #this is just creating a deck of cards, in standard order with the suits arranged alphabetically
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card=Card(suit, rank)
self.cards.append(card) #what you should be ending up here is 52 objects from the "Card" class

def shuffle(self):
shuffle(self.cards)

def main():
selfHand=[]
s,r=eval(input("Input your first downcard's suit and rank, separated by a comma" ))
card=Card(s,r)
selfHand.append(card)
deck.cards.remove(card)

再一次,一切正常(我省略了不相关的代码,如果有什么看起来有点不对劲——这就是为什么在 main 函数中有大缩进的原因)但是最后一行提示错误“ValueError: list.删除(x):x 不在列表中”

明确地说,牌组应该是一张纸牌列表。我正在尝试从牌组中移除一张特定的牌,仅此而已。以为它会很简单但已经吃掉了整个下午(公平地说,我对 python 和一般的编码都很陌生)

此时我尝试了无数种不同的方法,结果相似。

感谢帮助

最佳答案

您在 main 中创建的新卡与 deck 内阵列中的任何卡都不是同一对象,即使它与其中一张卡具有相同的花色和等级。

>>> c = Card(0,3)
>>> d = Card(0,3)
>>> c
<__main__.Card object at 0x0000000002025978>
>>> d
<__main__.Card object at 0x0000000002025908>
>>> c == d
False

您需要覆盖 Card 类中的 equals 和 not equals 方法,以便它知道如何比较两个 Card 实例。

def __eq__(self, other):
if isinstance(other, Card):
return self.suit == other.getSuit() and self.rank == other.getRank()
return NotImplemented
def __ne__(self, other):
if isinstance(other, Card):
return self.suit != other.getSuit() or self.rank != other.getRank()
return NotImplemented

然后你会得到你想要的输出:

>>> c = Card(0,3)
>>> d = Card(0,3)
>>> e = Card(1,4)
>>> c == d
True
>>> c != d
False
>>> c == e
False
>>> c != e
True
>>> deck = Deck()
>>> len(deck.cards)
52
>>> deck.cards.remove(c)
>>> len(deck.cards)
51

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com