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

2024-07-03 07:55:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在MakeCoin课上做了10个硬币。我把所有的硬币都放在硬币清单上。你知道吗

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

在程序的最后一部分,我使用coin迭代coinlist[],并使用pickup()方法从coinlist[]中删除coin对象名。它正在从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)

Tags: the对象infromself列表硬币this
2条回答

您在对列表进行迭代时正在修改它。坏主意。你知道吗

请尝试以下操作:

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

或者像@Asad说的那样

while coinlist:
    coinlist[0].pickup()

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

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

相关问题 更多 >