使用以下代码,我试图将所有卡片从套牌附加到字典中具有“酷”键的手上。
但由于某种原因,它只吸引了 3 次攻击中的 2 次。有人可以向我解释发生了什么吗?
attack = {"Name":"Attack","Cool":True}
defend = {"Name":"Defend"}
deck = [attack,attack,defend,defend,defend,attack]
hand = []
for card in deck:
try:
if card["Cool"] == True:
hand.append(deck.pop(deck.index(card)))
except Exception as e:
print (e)
print(hand)
#this Print will show that it has only appended 2 of the 3 attack dictionaries.
我也用一个while循环试过这个,认为我把索引逻辑搞砸了,但无济于事:
编辑:多亏了@Chrispresso,我才能够思考如何使 while 循环工作!我已经在代码中编辑了那部分
i = 0
while i < len(deck):
try:
if deck[i]["Cool"] == True:
hand.append(deck.pop(i))
i += 1 #commenting out this line does the trick as you should not be increasing the index when you are popping something from the list as this basically makes you jump two places instead of one.
except Exception as e:
i += 1
print (e)
非常感谢您提前提供的帮助!编辑:所以所需的输出将是
print(hand)
#[{"Name":"Attack","Cool":True},{"Name":"Attack","Cool":True},{"Name":"Attack","Cool":True}]
但目前的输出是:
print(hand)
#[{"Name":"Attack","Cool":True},{"Name":"Attack","Cool":True}]