遍历List和删除某些元素 [英] Iterate through a list and delete certain elements

查看:680
本文介绍了遍历List和删除某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作在我的电脑类的任务,而我有一个很难用code的一个部分。我会发布作业准则(粗体部分是我遇到的问题code):


  

您将创建一个模拟的蚁群,其用户将
  乘坐女王的角色谁的责任将是管理健康
  的殖民地。模拟将进行一个回合制的方式,
  其中每个旋转,用户可以选择花费precious食物资源
  更多的蚂蚁。


  
  

通过创建一个Python文件Ants.py有两个班开始:菌落
  蚂蚁


  
  

菌落类将有工蚁的列表(初始为空),一个
  食品的(最初10)3量和方法


  
  

      
  • breedWorker()

  •   
  • 步骤()

  •   
  • 清除()

  •   

  
  

breedWorker() 创建一个新的蚂蚁并将其添加到殖民地的名单的
  工蚁。创建一个工人成本殖民地的食物5。如果有
  是食物不足,消息应打印给用户并没有
  蚂蚁应该创建。


  
  

步骤() 处理殖民地每回合自动行为。
  即,此方法将控制每个蚂蚁中的行为
  殖民地。每回合每个蚂蚁应该吃从殖民地的食物一种食物
  供应。如果没有足够的食物,蚂蚁将失去的一个点
  健康替代。然后每个蚂蚁将搜寻食物(以下描述),
  发现任何食物都会被重新添加到殖民地的粮食供应。


  
  

清除() 扫描工蚁的名单,并与0健康的蚂蚁从列表中删除。对于每一个死蚂蚁加1,食品供应,
  因为蚂蚁回收!


  
  

我在与了解如何确保列表中的所有蚂蚁都健康,我不知道如何从零列表中删除健康蚂蚁麻烦。


  
  

蚂蚁类将有


  
  

      
  • 健康(初始设置为10)

  •   
  • A 饲料()

  •   

  
  

饲料() 随机确定的蚂蚁有同时开出搜索的运气
  食品每回合。


  
  

      
  • 有5%的几率使蚂蚁在一个可怕的事故死亡(健康
      = 0,返回任何食物)

  •   
  • 还有就是蚂蚁发现食物有40%的机会。发现的量应为1和5
  • 之间的随机数
      
  • 有一个
      50%的机会蚂蚁发现没有食物。

  •   
  • 并有一个5%的机会
      蚂蚁找到甜蜜蜜!她的健康补充(即设置为
      10)和她带回10食物殖民地!每步的结果
      蚂蚁的觅食既要打印的用户,并返回。

  •   

  
  

最后,你需要编写一个的main()方法来启动
  模拟和反复提示他们选择的用户。每回合
  用户应该滋生新的工作(为5成本的选择
  食品),或者什么也不做(没有新的蚂蚁)。您code应该检查用户的
  错误输入,并再次问,如果它是无效的。以下用户的
  动作(品种或不),菌落将产生一个一步的描述
  以上,最后,都死蚂蚁应该从殖民地被清除。
  仿真应该重复这样直到菌落出两者的
  蚂蚁和足够的食物,使更多的蚂蚁。


这是我的code:

 进口随机类殖民地(对象):    高清__init __(个体经营):
        Colony.food = 10
        Colony.numWorkerAnts = 0
        Colony.workerAnts = []     高清breedWorker(个体经营):
         打印(育种工作者......)
         Colony.numWorkerAnts + = 1
         Colony.food - = 5
         Colony.workerAnts.append(1)
         如果(Colony.food小于5):
            打印(对不起,你没有足够的食物滋生新的工蚁!)     DEF步骤(个体经营):
         因为我在范围(0,LEN(Colony.workerAnts)):
            Colony.food - = 1蚂蚁类(对象):    高清__init__self(个体经营):
    Ant.health = 10    高清饲料(个体经营):
    foodFound = random.random()
    如果(foodFound&下; = 0.05):
       打印(蚂蚁死亡的事故!)
       Ant.health = 0
    如果(foodFound> 0.05 foodFound< 0.40):
       amountFood = random.randint(1,5)
       打印(蚂蚁发现+ STR(amountFood)+食品。)
       Colony.food + = amountFood
    如果(foodFound> = 0.40和foodFound< 0.95):
       打印(蚂蚁工人返回两手空空。)
    如果(foodFound> = 0.95):
       打印(您的蚂蚁发现甜蜜蜜!蚂蚁返回+ STR(amountFood)+的群体和健康恢复到+ STR(self.health)+!)
       amountFood = 10
       Ant.health = 10
       Colony.food = amountFood + Colony.food高清的main():
    殖民地=殖民地()
    蚂蚁蚂蚁=()
    而(Colony.numWorkerAnts> = 1或Colony.food> = 5):
    打印(您的殖民地有+ STR(Colony.numWorkerAnts)+蚂蚁+ STR(Colony.food)+食品,陛下。)
    打印(你想怎么办?)
    打印(0什么都不做)
    打印(1.养殖工人(费5食物))
    提示='>
    选择= INT(的raw_input(提示))    如果(选择== 1):
        colony.breedWorker()
        colony.step()
        因为我在范围(0,LEN(Colony.workerAnts)):
            ant.forage()
    其他:
        因为我在范围(0,LEN(Colony.workerAnts)):
            ant.forage()
            colony.step()
主要()


解决方案

目前,你这是一切的类属性,在类的所有实例之间共享,当您使用 ClassName.attr 。相反,你应该使用 self.attr 来使一切实例属性:

 类殖民地(对象):    高清__init __(个体经营):
        self.food = 10
        self.workerAnts = []#numWorkerAnts只是LEN(workerAnts)

请注意,你应该改变 breedWorker 来实际上是一个新的蚂蚁实例添加到<$ C $名单C> self.workerAnts ;此刻,它仅递增计数。

要减少殖民地与健康的蚂蚁,你可以使用列表COM prehension:

  self.workerAnts = [在self.workerAnts蚂蚁蚂蚁,如果ant.health]

I'm working on an assignment in my computer class, and I'm having a hard time with one section of the code. I will post the assignment guidelines (the bolded part is the code I'm having issues with):

You are going to create a simulated ant colony, in which the user will take the role of the queen who's duty it will be to manage the health of the colony. The simulation will proceed in a turn-based fashion, where each turn the user can choose to spend precious food resources on more ants.

Begin by creating a python file Ants.py with two classes: Colony and Ant.

The Colony class will have a list of worker ants (initially empty), an amount of food (initially 10), and 3 methods:

  • breedWorker()
  • step()
  • purge()

breedWorker() creates a new Ant and adds it to the colony's list of worker ants. Creating a worker costs 5 of the colony's food. If there is insufficient food, a message should be printed to the user and no ant should be created.

step() handles the automatic behaviour of the colony for each turn. Namely, this method will control the behaviour of each ant in the colony. Each turn each ant should eat one food from the colony's food supply. If there is not enough food, the ant will lose one point of health instead. Each ant will then forage for food (described below), and any food found will be added back into the colony's food supply.

purge() scans the list of worker ants, and any ants with 0 health are removed from the list. For each dead ant add 1 to the food supply, because ants recycle!

I'm having trouble with understanding how to make sure that all the ants in the list have health, and I'm unsure about how to delete the ants with zero health from the list.

The Ant class will have

  • Health (initially set to 10)
  • A forage() method

forage() determines randomly the luck an ant has while out searching for food each turn.

  • There is a 5% chance that the ant dies in a horrible accident (health = 0, return no food)
  • There is a 40% chance that the ant finds food. The amount found should be a random number between 1 and 5.
  • There is a 50% chance that the ant finds no food.
  • And there is a 5% chance that the ant finds sweet nectar! Her health is replenished (i.e., set to 10) and she brings back 10 food to the colony! The results of each ant's foraging should be both printed for the user and returned.

Finally, you will need to write a main() method to start the simulation and repeatedly prompt the user for their choices. Each turn the user should have the option to breed a new worker (for a cost of 5 food), or do nothing (no new ants). Your code should check the user's input for errors and ask again if it was invalid. Following the user's action (breed or not), the colony will take one 'step' as described above, and lastly, all dead ants should be purged from the colony. Simulation should repeat like this until the colony is out of both ants and enough food to make more ants.

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和删除某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆