2014-05-13 87 views
0

的Python 2.7.5list.remove(X):X不在列表中

我找不到這對其他問題,所以我會問...

程序應該:

  1. 創建一個有機體羣體()s。

  2. 選擇兩個從人口隨機生物

  3. 如果這兩種生物都是「黑」,將其刪除,並創建一個新的「黑」生物

實際發生的:

當清單非常清晰時,我的程序給出了「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() 

回答

4

我懷疑你得到你的錯誤描述你什麼時候隨機選擇和父母一樣的Organism。您在第一次致電list.remove時將其從名單中刪除,但第二次失敗,因爲Organism已經消失。

我不確定你是否打算讓同一個生物體被挑選兩次。如果是這樣,你需要把支票上的第二次調用remove

if parent2 is not parent1: 
    population.remove(parent2) 

如果,另一方面,你永遠要選擇相同Organism兩次,你需要改變你如何選擇你的parent s。這裏有一個簡單的修復,但也有其他的方法來做到這一點:

parent1, parent2 = random.sample(population, 2) 
+0

upvote用於提示''sample''。 – aruisdante

+0

啊!謝謝你的回答,你現在有權在我面前擊中我! – FrigidDev

+1

你也應該使用'if parent1不是parent2',因爲你想知道它們是否是相同的實例。 – Davidmh

2

如果parent1 == parent2?然後你刪除這兩個parent1和parent2在這一行:

population.remove(parent1)

和parent2真的aren`t列表

+0

沒錯,那就是當失敗究竟發生了什麼。 – dano

+0

如果人口規模很小,發生這種情況的可能性相當高。在這種情況下,最好的情況是4分之1,最差的情況是2分之1。 – aruisdante

相關問題