[英]Counting Loop Iterations (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
(死)還是已經足夠老化。
抱歉,如果這是一個簡單的問題,但是循環不是我的強項……我一直在閱讀理解等內容,但是任何其他材料也將不勝感激。 更何況我的問題的答案! 非常感謝。
可能不希望的一件事:當您將列表傳遞給list()時,將返回列表的副本( http://docs.python.org/2/library/functions.html#list )。 因此,當您對list(petri_dish)中的x進行運算時,您將從列表的副本中獲取元素,而不是實際列表中的元素。
我之所以這么說是因為for循環中的第一行代碼是x.age + =1。這不會增加petri_dish列表中項目的年齡。 由於您將年齡作為從列表中刪除項目的決定因素,因此這似乎是一個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.