gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:45:56 24 4
gpt4 key购买 nike

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

关于python - 未能正确遍历我的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7853898/

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