Python 2.7.5
我无法在其他问题上找到这个,所以我会问......
该计划应该:
创建一个有机体群体()s。
从人口中选择两个随机生物
如果这两种生物都是"黑色",删除它们,并创建一个新的"黑色"生物体
实际发生的事情:
我的程序正在给出一个" list.remove(x):x不在列表"中,当它非常明显地在列表中时。 错误仅发生在第50行(而不是49): Python表示它无法将其从列表中删除,但它不应该首先尝试将其从列表中删除(第44行)。
我难以理解为什么会这样做,我错过了一些明显的东西吗?
import random as r
import os
import sys
import time
class Organism(object):
def __init__(self, color_code):
self.color_code = color_code
self.color = None
if self.color_code == 0:
self.color = 'black'
if self.color_code == 1:
self.color = 'white'
population_count = []
#Generates initial population
for organism in range(r.randint(2, 4)):
org = Organism(0)
population_count.append(org)
#Prints the color_traits of the different organisms
print "INITIAL"
for color in population_count:
print color.color
print "INITIAL"
class PopulationActions(object):
def __init__(self, pop):
self.population_count = pop
def Crossover(self, population):
#Select 2 random parents from population
parent1 = population[r.randint(0, (len(population) -1))]
parent2 = population[r.randint(0, (len(population) -1))]
#If both parents are 'black' add organism with black attribute and kill parents
if parent1.color == "black" and parent2.color == "black":
if parent1 in population and parent2 in population:
org = Organism(0)
population.append(org)
print "__________ADDED ORGANISM_______________"
population.remove(parent1)
population.remove(parent2)
print "__________KILLED PARENTS_______________"
else:
pass
#Main loop
pop = PopulationActions(population_count)
generation = 0
while generation <= 3:
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
pop.Crossover(population_count)
#Print colors of current population
for color in population_count:
print color.color
generation += 1
raw_input()
答案 0 :(得分:4)
我怀疑当你随机选择与父母一样的Organism
时,你会收到你所描述的错误。您第一次调用list.remove
时会将其从列表中删除,但第二次调用失败,因为Organism
已经消失。
我不确定你是否打算将同一个生物体挑选两次。如果是这样,您需要检查对remove
的第二次调用:
if parent2 is not parent1:
population.remove(parent2)
另一方面,如果您再也不想选择相同的Organism
两次,则需要更改选择parent
的方式。这是一个简单的修复,但还有其他方法可以做到:
parent1, parent2 = random.sample(population, 2)
答案 1 :(得分:2)
如果parent1 == parent2怎么办?然后在此行中删除parent1和parent2:
population.remove(parent1)
和parent2确实不在列表中