Skip to main content
 首页 » 编程设计

python之未能正确遍历我的列表

2025年05月04日15webabcd

奇怪的是,我使用的是内置迭代 O.o 的 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]])) 

奇怪的是,这是标准输出的输出:

['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'] 

您可以清楚地看到,第一个列表中有名称(具体为:'Tools'、'Pottery'、'Clothing')

输出的第二部分没有打印任何内容,实际上它们留在了列表中(顺便说一句,这三个符号的符号中都有“CASTLE”,应该被删除)。

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

请您参考如下方法:

您不应该在迭代列表时从列表中删除项目。

遍历列表的副本:

for card in self.thegame.game_deck.deck[0][:]: 
                                          ^^^ copies the list 

或者创建一个包含您要保留的项目的新列表,然后重新分配它:

game_deck = self.thegame.game_deck 
game_deck.deck[0] = [card for card in game_deck.deck[0] if 'CASTLE' in card.symbols]