‘,’服装’,‘城邦s’,‘射箭’,’ 农业 </跨度> “]
写作被删除了车轮没有被拆除帆船被移走了桨没有被移除神秘主义没有消除金属加工没有被删除砌体被 不被删除没有去除驯化法典已被删除城市国家没有被删除射箭没有被移除
农业 </跨度> 去掉了
[‘工具’,‘轮子’,‘陶器’,‘桨’,‘神秘主义’
迭代删除的另一个常见替代方法是标记待删除的项目(改变列表中的值但不更改列表长度),然后进行第二次高速传递以过滤掉无保证的卡:
# 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 i, card in enumerate(self.thegame.game_deck.deck[0]): if 'CASTLE' not in card.symbols: self.thegame.game_deck.deck[0][i] = None print(card.name + ' was marked to be removed') else: print(card.name + ' was not removed') # This does the actual removal self.thegame.game_deck.deck[0][:] = filter(None, self.thegame.game_deck.deck[0]) # 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]]))
在迭代它时,不应该从列表中删除项目。
迭代a 复制 列表:
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]
您正在修改您正在迭代的列表。这是一个坏主意。相反,将您想要保留的那些附加到单独的列表中,并在最后将其重新分配给卡。
详细说明执行此操作时会发生什么:
In [99]: l = range(5) In [100]: for i in l: l.remove(i) print list(enumerate(l)) .....: .....: [(0, 1), (1, 2), (2, 3), (3, 4)] [(0, 1), (1, 3), (2, 4)] [(0, 1), (1, 3)]
当您更改列表时,您正在更改索引引用哪个项目,您可以使用该值查看 4 在上面的列表中。
4
您正在从您正在迭代的列表中删除项目。使用具有CASTLE图标的卡创建新列表,而不是删除具有图标的卡。