如何使用Python按照顺序从列表中移除对象

2024-06-01 01:32:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数throw_cards,它接受一个手对象,其中包含一定数量的卡片对象,打印一条消息,并从self.cards列表中删除卡片。 这就是我目前拥有的:

ability = {'Clubs':5, 'Diamonds':6, 'Hearts':7, 'Spades':8}

class Hand(Deck):
        """Represents a hand of playing cards."""
        def __init__(self, label=''): #name for hand? idk
            self.cards = []
            self.label = label

        def throw_cards(self):
            for card in self.cards:
                print(card, 'deals', ability[Card.suit_names[card.suit]],
                      'damage!')
                self.cards.remove(self.cards[0])
q = Hand()
w= Deck()
w.shuffle()
w.move_cards(q, 6)     

以这种方式使用函数

>>> q.throw_cards()
King of Hearts deals 7 damage!
5 of Clubs deals 5 damage!
10 of Hearts deals 7 damage!
>>> print(q)
3 of Diamonds
10 of Hearts
10 of Spades

问题似乎是,它没有按正确的顺序取出卡片。我也尝试过使用.pop().remove()的不同索引,但无法打印然后从手上取出卡片。另外,请让我知道,如果这个问题本身是好的,在格式和信息方面!我是个新手。你知道吗


Tags: of对象函数selfcardlabelcardsthrow
1条回答
网友
1楼 · 发布于 2024-06-01 01:32:31

您正在修改正在迭代的列表,这导致了您看到的问题。你知道吗

既然您似乎想删除所有卡片,为什么不在完成打印后将self.cards重新绑定到一个空列表:

def throw_cards(self):
    for card in self.cards:
        print(card, 'deals', ability[Card.suit_names[card.suit]], 'damage!')
    self.cards = []

相关问题 更多 >