为什么list.remove()无法“正常”工作?

时间:2019-04-28 23:26:26

标签: python

我有一个包含4个列表和一个列表容器的类(点)。在我的主目录中,我试图从列表之一中弹出一个值。如果列表为空,则将其从容器中删除。一切正常,但是有时输出显示它尝试从容器中删除与以前相同的列表。为什么以这种方式工作?

我的代码:

class Points():

    def __init__(self):
        points = ["One", "Two", "Three", "Four", "Five"]
        self.A = points.copy()
        self.B = points.copy()
        self.C = points.copy()
        self.D = points.copy()
        self.container = [self.A, self.B, self.C, self.D]

    def getPoint(self, letter, index):
        try:
            res = self.container[letter].pop(index-1)

            if (len(self.A) == 0) and (self.A in self.container):
                print("OUT OF A")
                self.container.remove(self.A)
            if (len(self.B) == 0) and (self.B in self.container):
                print("OUT OF B")
                self.container.remove(self.B)
            if (len(self.C) == 0) and (self.C in self.container):
                print("OUT OF C")
                self.container.remove(self.C)
            if (len(self.D) == 0) and (self.D in self.container):
                print("OUT OF D")
                self.container.remove(self.D)
        except:
            return -1
        return res

if __name__ == "__main__":
    m_Points = Points()

    for item in range(25):
        try:
            letterCode = randint(0,len(m_Points.container)-1)
            letter = m_Points.container[letterCode]
            index = randint(0, len(letter) )
            print("#{}. {}".format(item, m_Points.getPoint(letterCode, index) ))
        except:
            print("No more points")
            break

输出:

#0. Four
#1. One
#2. Three
#3. One
#4. Five
#5. Three
#6. Five
#7. Four
#8. Four
#9. Two
OUT OF B
#10. Two
#11. Two
OUT OF A           <--- First time A
#12. One
#13. Five
#14. Four
#15. Three
OUT OF A           <--- A AGAIN?
#16. One
#17. Five
#18. Two
OUT OF A           <--- and again...
#19. Three
No more points

1 个答案:

答案 0 :(得分:4)

原因是inremove的工作方式。

您的困惑可能源于一个误解,即in询问特定容器是否包含特定对象,然后删除移除特定对象,等等。您打电话说.remove(self.A),则希望* list指向的self.A被删除。

但是,发生的事情是in只是查看容器中是否存在具有特定值的对象,而remove会删除容器中具有该值的第一个对象。在这两种情况下,都不必是self.A只是一个具有相同值的对象

因此,最终,我们将获得以下内容:

self.A = ['First']
self.container = [['First'], ['First'], ['First']]

# ...check and remove goes here

在这种情况下,由于self.container 确实包含一个list且值等于self.A { {1}}不为空,第一笔检查通过,您到达self.A。然后,删除第一个print('OUT OF A')但是在下一次迭代中条件仍然成立,因为所有其余的list都具有相同的值!