为什么此“ for”循环在Python中随机停止

时间:2019-09-19 11:01:59

标签: python

在我一直在研究的代码段中,有一个for循环,在该循环中,列表中的每个项目都会循环执行最终删除一个项目并再次返回的过程。

当我运行代码时,它会从列表开头的30个项目中的剩余10个项目停止。

cards_blue = ["b1","b2","b3","b4","b5","b6","b7","b8","b9","b10"]
cards_red = ["r1","r2","r3","r4","r5","r6","r7","r8","r9","r10"]
cards_yellow = ["y1","y2","y3","y4","y5","y6","y7","y8","y9","y10"]
deck = cards_blue + cards_red + cards_yellow
random.shuffle(deck)
for card in deck:

然后在纸牌游戏过程结束时:

    if not deck:
        if card_score1 > card_score2:
            print("Player 1 is the final winner, they have the most cards")
        elif car_score2 > card_score1:
            print("Player 2 is the final winner, they have the most cards")
        print("Deck is empty")

在游戏的所有30个循环结束时,它将使用计分系统决定获胜者,但在完成之前停下来。 我不确定为什么会这样,有人可以帮助解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

如果要编辑列表,则应考虑切换到while循环,例如:

while deck:
    card = deck.pop(0)
    ...