为什么.pop()最终会停止并且在列表为空之前不继续从列表中删除项目?

时间:2019-05-10 20:25:46

标签: python random shuffle pop

我正在尝试构建纸牌游戏手模拟器。 我希望能够整理一张纸牌列表(我假设是随机进口),然后将纸牌从纸牌顶部取出,然后将它们放到我的手中。我希望能够随心所欲地绘画。

问题是当我使用.pop()来执行此操作时,它将从随机列表中删除几行内容,但最终停止,然后仅在列表中保留2项。当我查阅文档时,默认说.pop()会删除位置0处的项目,所以我不知道为什么它不会继续。

现在,我正在尝试使用.pop()方法。我是python新手,所以可能有更好的方法,我只是不知道是否有更好的方法。无论如何,我试图理解为什么.pop()不能解决此问题,而文档也不能提供完全的帮助。

    '''the for-loop is supposed to shuffle my cards, and then keep plucking one off of the top until there are no more cards in the deck'''

import random
hand = [1,2,3,4,5]
random.shuffle(hand)
for i in hand:
    card = hand.pop(0)
    print(card)
    print(hand)

我实际上得到的是:     1个     [4、5、3、2]     4     [5、3、2]     5     [3,2]

我想要得到什么:         1个     [4、5、3、2]     4     [5、3、2]     5     [3,2]     3     [2]     2     []

1 个答案:

答案 0 :(得分:2)

一般说明:

您要在迭代列表内容的同时对其进行修改。当您这样做时,会发生坏事。

更多技术说明:

for循环for i in hand在循环开始时只求hand一次。但是每次循环时,您都要从列表中删除项目,因此for循环的结果现在与列表的当前状态不同步。

尝试以下方法:

import random
hand = [1,2,3,4,5]
random.shuffle(hand)
while hand:
    card = hand.pop(0)
    print(card)
    print(hand)