我是python线程的新手,我找不到任何答案。如果是重复的问题,对此表示抱歉。 我有一个这样的线程类:
class Ant(Thread):
def __init__(self, start_item, possible_items, backpack_limit, pheromone_map, alpha, beta, eta):
Thread.__init__(self)
self.start_item = start_item
self.item = start_item
self.possible_items = possible_items
self.selected_items = []
self.backpack_limit = backpack_limit
self.weight_sum = 0
self.backpack_value = 0
self.pheromone_map = pheromone_map
self.alpha = alpha
self.beta = beta
self.eta = eta # (weight/value)
# append start location to route, before doing random walk
self.add_backpack(start_item)
self.tour_complete = False
def run(self):
while self.possible_items and self.is_remaining_space_feasible():
next_item = self.pick_item()
self.item = next_item
self.add_backpack(next_item)
self.tour_complete = True
def add_backpack(self, next_item):
self.update_items(next_item)
self.update_backpack(next_item)
def update_items(self, next_item):
self.selected_items.append(next_item)
self.possible_items.remove(next_item)
def update_backpack(self, next_item):
self.weight_sum += next_item.get_weight()
self.backpack_value += next_item.get_value()
,然后在另一个类中创建一堆实例,如下所示:
ants = [Ant(self.items[random.randint(0, len(self.items) - 1)], self.items, self.backpack_limit, self.pheromone_matrix, self.alpha, self.beta, self.eta) for _ in range(self.ant_count)]
如您所见,当我创建一个ant实例时,它称为add_backpack函数,并在某些时候完成了这段代码工作self.possible_items.remove(next_item)
,程序完成了初始化步骤并创建了下一个实例。但是对于下一个实例possible_items
已经删除了该项目,这导致了 list.remove(x):x not in list 错误。我尝试了深度复制,但无法正常工作。