未能正确遍历我的列表

2024-04-26 22:14:52 发布

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

奇怪的是,我使用的是Python内置的迭代O.O

我有一门课叫卡片。卡片上有一个名字和一系列符号(字符串)。你知道吗

这是我的一段代码(所有打印都是为了调试)

    # 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]]))

奇怪的是,这是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']

你可以清楚地看到,第一个列表中有一些名字(特别是:“工具”、“陶器”、“衣服”)

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

有人能看到我错过了什么吗?你知道吗


Tags: ofthenameinselfgamefornot
2条回答

您正在从要迭代的列表中删除项。用带有城堡图标的卡片创建一个新列表,而不是删除带有城堡图标的卡片。你知道吗

在遍历列表时,不应该从列表中删除项。你知道吗

迭代列表的副本

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]

您正在修改正在迭代的列表。这是个坏主意。相反,将你想保留的内容附加到一个单独的列表中,并将其重新分配到最后的卡片中。你知道吗

相关问题 更多 >