本文介绍了遍历List和删除某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的工作在我的电脑类的任务,而我有一个很难用code的一个部分。我会发布作业准则(粗体部分是我遇到的问题code):
This is my code:
import random
class Colony(object):
def __init__(self):
Colony.food = 10
Colony.numWorkerAnts = 0
Colony.workerAnts = []
def breedWorker(self):
print ("Breeding worker...")
Colony.numWorkerAnts += 1
Colony.food -= 5
Colony.workerAnts.append(1)
if (Colony.food < 5):
print ("Sorry, you do not have enough food to breed a new worker ant!")
def step(self):
for i in range(0,len(Colony.workerAnts)):
Colony.food -= 1
class Ant(object):
def __init__self(self):
Ant.health = 10
def forage(self):
foodFound = random.random()
if (foodFound <= 0.05):
print("Ant has died in an accident!")
Ant.health = 0
if (foodFound > 0.05 and foodFound < 0.40):
amountFood = random.randint(1,5)
print("Ant finds "+str(amountFood)+" food.")
Colony.food += amountFood
if (foodFound >= 0.40 and foodFound < 0.95):
print("Ant worker returns empty handed.")
if (foodFound >= 0.95):
print("Your ant finds sweet nectar! Ant returns "+str(amountFood)+" to the colony and health is restored to "+str(self.health)+"!")
amountFood = 10
Ant.health = 10
Colony.food = amountFood + Colony.food
def main():
colony = Colony()
ant = Ant()
while (Colony.numWorkerAnts >= 1 or Colony.food >= 5):
print ("Your colony has "+str(Colony.numWorkerAnts)+" ants and "+str(Colony.food)+" food, Your Majesty.")
print ("What would you like to do?")
print ("0. Do nothing")
print ("1. Breed worker (costs 5 food)")
prompt = '> '
choice = int(raw_input(prompt))
if (choice == 1):
colony.breedWorker()
colony.step()
for i in range(0, len(Colony.workerAnts)):
ant.forage()
else:
for i in range(0, len(Colony.workerAnts)):
ant.forage()
colony.step()
main()
解决方案
At the moment, you are making everything a class attribute, shared amongst all instances of the class, as you use ClassName.attr
. Instead, you should use the self.attr
to make everything an instance attribute:
class Colony(object):
def __init__(self):
self.food = 10
self.workerAnts = [] # numWorkerAnts is just len(workerAnts)
Note that you should alter breedWorker
to actually add a new Ant
instance to the list of self.workerAnts
; at the moment, it only increments the count.
To reduce the colony to ants with health, you can use a list comprehension:
self.workerAnts = [ant for ant in self.workerAnts if ant.health]
这篇关于遍历List和删除某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!