优化代码:def crossSol(model): sol_list=copy.deepcopy(model.sol_list) model.sol_list=[] while True: f1_index = random.randint(0, len(sol_list) - 1) f2_index = random.randint(0, len(sol_list) - 1) if f1_index!=f2_index: f1 = copy.deepcopy(sol_list[f1_index]) f2 = copy.deepcopy(sol_list[f2_index]) if random.random() <= model.pc: cro1_index=int(random.randint(0,len(model.demand_id_list)-1)) cro2_index=int(random.randint(cro1_index,len(model.demand_id_list)-1)) new_c1_f = [] new_c1_m=f1.node_id_list[cro1_index:cro2_index+1] new_c1_b = [] new_c2_f = [] new_c2_m=f2.node_id_list[cro1_index:cro2_index+1] new_c2_b = [] for index in range(len(model.demand_id_list)):#遍历长度 if len(new_c1_f)<cro1_index: if f2.node_id_list[index] not in new_c1_m: new_c1_f.append(f2.node_id_list[index]) else: if f2.node_id_list[index] not in new_c1_m: new_c1_b.append(f2.node_id_list[index]) for index in range(len(model.demand_id_list)): if len(new_c2_f)<cro1_index: if f1.node_id_list[index] not in new_c2_m: new_c2_f.append(f1.node_id_list[index]) else: if f1.node_id_list[index] not in new_c2_m: new_c2_b.append(f1.node_id_list[index]) new_c1=copy.deepcopy(new_c1_f) new_c1.extend(new_c1_m) new_c1.extend(new_c1_b) f1.nodes_seq=new_c1 new_c2=copy.deepcopy(new_c2_f) new_c2.extend(new_c2_m) new_c2.extend(new_c2_b) f2.nodes_seq=new_c2 model.sol_list.append(copy.deepcopy(f1)) model.sol_list.append(copy.deepcopy(f2)) else: model.sol_list.append(copy.deepcopy(f1)) model.sol_list.append(copy.deepcopy(f2)) if len(model.sol_list)>model.popsize: break
时间: 2023-12-03 11:03:22 浏览: 89
Python库 | zope.copy-4.1.0.tar.gz
可以尝试使用列表推导式和切片来简化代码,同时也可以尝试使用更加有意义的变量名来提高可读性。以下是优化后的代码:
```
def crossSol(model):
sol_list = copy.deepcopy(model.sol_list)
model.sol_list = []
while True:
f1_index, f2_index = random.sample(range(len(sol_list)), 2)
f1, f2 = copy.deepcopy(sol_list[f1_index]), copy.deepcopy(sol_list[f2_index])
if random.random() <= model.pc:
cro1_index, cro2_index = sorted(random.sample(range(len(model.demand_id_list)), 2))
new_c1_m, new_c2_m = f1.node_id_list[cro1_index:cro2_index+1], f2.node_id_list[cro1_index:cro2_index+1]
new_c1_f = [node for node in f2.node_id_list[:cro1_index] if node not in new_c1_m]
new_c1_b = [node for node in f2.node_id_list[cro2_index+1:] if node not in new_c1_m]
new_c2_f = [node for node in f1.node_id_list[:cro1_index] if node not in new_c2_m]
new_c2_b = [node for node in f1.node_id_list[cro2_index+1:] if node not in new_c2_m]
new_c1, new_c2 = new_c1_f + new_c1_m + new_c1_b, new_c2_f + new_c2_m + new_c2_b
f1.nodes_seq, f2.nodes_seq = new_c1, new_c2
model.sol_list.extend([copy.deepcopy(f1), copy.deepcopy(f2)])
if len(model.sol_list) >= model.popsize:
break
```
这里使用了 `random.sample` 函数来随机选择两个不同的索引,用 `sorted` 函数来获取两个索引的有序列表,使用列表推导式和切片来生成新路径,使用更加有意义的变量名来提高代码的可读性。
阅读全文