的Python 2.7.5list.remove(X):X不在列表中
我找不到這對其他問題,所以我會問...
程序應該:
創建一個有機體羣體()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()
upvote用於提示''sample''。 – aruisdante
啊!謝謝你的回答,你現在有權在我面前擊中我! – FrigidDev
你也應該使用'if parent1不是parent2',因爲你想知道它們是否是相同的實例。 – Davidmh