我有一个关于在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(死亡)还是已经足够老了。在
抱歉,如果这是一个简单的问题,但循环不是我的强项。。。我一直在阅读理解和类似的东西,但任何额外的材料也将不胜感激。更不用说回答我的问题了!非常感谢。在