无法正确迭代我的列表

Los*_*_DM 1 python list

奇怪的是我正在使用迭代Oo内置的Python

我有一个名为Card的课程.除其他外,卡还有一个名称和一个符号列表(字符串).

这是我的一段代码(所有打印用于调试目的)

    # This prints all the names of the cards in the deck before the iteration.
    print(str([card.name for card in self.thegame.game_deck.deck[0]]))

    for card in self.thegame.game_deck.deck[0]:
        if 'CASTLE' not in card.symbols: 
            self.thegame.game_deck.deck[0].remove(card)
            print(card.name + ' was removed')
        else: print(card.name + ' was not removed')

    # This prints all the names of the cards in the deck after the iteration.                
    print(str([card.name for card in self.thegame.game_deck.deck[0]]))
Run Code Online (Sandbox Code Playgroud)

奇怪的是,这是stdout的输出:

['Writing', 'Tools', 'The Wheel', 'Sailing', 'Pottery', 'Oars', 'Mysticism', 'Me
talworking', 'Masonry', 'Domestication', 'Code of Laws', 'Clothing', 'City State
s', 'Archery', 'Agriculture']

Writing was removed
The Wheel was not removed
Sailing was removed
Oars was not removed
Mysticism was not removed
Metalworking was not removed
Masonry was not removed
Domestication was not removed
Code of Laws was removed
City States was not removed
Archery was not removed
Agriculture was removed


['Tools', 'The Wheel', 'Pottery', 'Oars', 'Mysticism', 'Metalworking', 'Masonry'
, 'Domestication', 'Clothing', 'City States', 'Archery']
Run Code Online (Sandbox Code Playgroud)

你可以清楚地看到,第一个清单中有名字(特别是:'工具','陶器','服装')

在输出的第二部分中没有任何内容打印出来,实际上它们都留在列表中(所有三个,顺便说一下,它们的符号中都有'CASTLE',应该删除).

有人能看出我错过了什么吗?

Mar*_*ers 7

在迭代它时,不应该从列表中删除项目.

迭代列表的副本:

for card in self.thegame.game_deck.deck[0][:]:
                                          ^^^ copies the list
Run Code Online (Sandbox Code Playgroud)

或者使用要保留的项目创建新列表,然后重新分配:

game_deck = self.thegame.game_deck
game_deck.deck[0] = [card for card in game_deck.deck[0] if 'CASTLE' in card.symbols]
Run Code Online (Sandbox Code Playgroud)