计数循环迭代(Python)

时间:2013-10-04 14:42:51

标签: python loops object iteration

我有一个关于在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(死)还是有年龄足够。

对不起,如果这是一个简单的问题,但循环不是我的强项......我一直在阅读理解等等,但任何其他材料也将受到赞赏。更不用说回答我的问题了!非常感谢。

1 个答案:

答案 0 :(得分:1)

可能有或没有意图:当您将列表传递给list()时,将返回列表的副本(http://docs.python.org/2/library/functions.html#list)。因此,当您在列表中使用x(petri_dish)时,您将从列表的副本中获取元素,而不是实际列表。

我提到这个的原因是for循环中的第一行代码是x.age + = 1.这不会增加petri_dish列表中项目的年龄。由于您使用年龄作为从列表中删除项目的决定因素,这似乎是一个问题。

相关问题