计数循环迭代(Python)

2024-05-15 02:07:49 发布

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

我有一个关于在Python中计算循环迭代次数的问题。我创建的对象在每次迭代中都会“老化”,并且应该在某个特定的年龄“死亡”,但有时它们会活得更长。以下是我的程序片段:

def reproduce():
    class Offspring(Species):
        def __init__(self,name,life,attack,move,location,status,species,age):
            area = 1000
            self.name = name
            self.life = life
            self.attack = attack
            self.move = move
            self.location = [random.randint(1,area),random.randint(1,area)]
            self.status = 1
            self.species = 'simple'
            self.age = 1
    for z in [y for y in petri_dish if y.status == 1 and y.life >= 50 and y.species == 'simple']:
        petri_dish.append(Offspring('g' + str(turn/250)+'#'+str(z.name),(random.randint(int(z.life/2),z.life)),(random.randint(int(z.attack/2),z.attack)),(random.randint(int(z.move/2),z.move)),0,1,0,0))
        print 'g' + str(turn/250)+'#'+str(z.name), 'was born.'
def move_around():
    for x in list(petri_dish):
        x.age += 1
        if x.status == 0 or (x.species == 'species' and x.age >= 750) or (x.species == 'predator' and x.age >= 3000):
            print str(x.name) + ' expired. Cells left: ' + str(len(petri_dish))            
            petri_dish.remove(x)
        else:
            x.relocate()
            x.target()
            if len(petri_dish) >= 75:
                for x in list(petri_dish):
                    if x.life < int(turn/25):
                        x.status = 0 
    if turn % 250 == 0:
        reproduce()

while len([y for y in petri_dish if y.status == 1]) > 1:
    turn += 1     
    move_around()

后代是一个simple物种,应该在750岁或更高的年龄死亡——理想的情况是750岁,但这是问题的一部分。我还不知道如何迭代我的对象列表(即petri_dish),并在迭代的任何时候删除某些对象,无论它们是在status = 0(死亡)还是已经足够老了。在

抱歉,如果这是一个简单的问题,但循环不是我的强项。。。我一直在阅读理解和类似的东西,但任何额外的材料也将不胜感激。更不用说回答我的问题了!非常感谢。在


Tags: nameselfforagemoveifstatusrandom
1条回答
网友
1楼 · 发布于 2024-05-15 02:07:49

有一件事可能是有意的,也可能不是故意的:当您将一个列表传递给list()时,将返回该列表的一个副本(http://docs.python.org/2/library/functions.html#list)。所以当你对列表中的x(petri_dish)进行操作时,你是从列表的副本中获取元素,而不是从实际列表中获取元素。在

我提到这一点的原因是for循环中的第一行代码是x.age+=1。这不会增加petri_培养皿列表中物品的年龄。因为你用年龄作为从列表中删除项目的决定因素,这似乎是个问题。在

相关问题 更多 >

    热门问题