为什么列表上的所有硬币都不会被删除?

时间:2014-03-27 13:55:00

标签: python list class object

我从MakeCoin班制作10个硬币物品。我将所有硬币对象放在硬币清单上[]。

我还在MakeCoin类中创建了一个名为pickup的方法,这个类将从coinlist []中删除该对象。

在程序的后半部分,我用硬币迭代coinlist [],然后用方法pickup()从coinlist []中删除硬币对象名称。它正在从coinlist []中删除硬币,但仍然有5个硬币对象名称保留在列表中(偶数名称) - 我真的不明白他们为什么留在列表中,我怎么能删除整个列表?

from random import randint

class MakeCoin(object):
    def __init__(self,sprite):
        #give the coin random x,y location
        self.x=randint(0,10)
        self.y=randint(0,10)
        self.sprite=sprite

    def show(self):
        #show the coin location
        print "x:%d y:%d" %(self.x,self.y)

    def pickup(self):
        #you've picked up this coin, so delete it from list
        coinlist.remove(self)

#generate 10 coins  
coinlist=[]
for x in range(0,10):
    coinlist.append(MakeCoin(1))

#this will show that there are 10 coins in list 
print len(coinlist)


#this will let you pickup all the coins from the list(remove coins from coinlist) 
for coin in coinlist:
    #delete the coin !
    coin.pickup()

#in my opinion, this should print out 0 ...but it say's 5 ! (there -
#are still five coins on the list, the evencoins are still there...how to solve this ?
print len(coinlist)

2 个答案:

答案 0 :(得分:1)

问题是您正在修改正在迭代的列表。这是一个坏主意。避免这种情况的一种简单方法是创建一个这样的新列表:

for coin in coinlist[:]:
    coin.pickup()

答案 1 :(得分:1)

您正在迭代它时修改列表。坏主意。

请改为尝试:

for i in range(len(coinlist)):
    coinlist[0].pickup()

或者@Asad说

while coinlist:
    coinlist[0].pickup()