降低这段代码重复率: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 19:03:36 浏览: 129
可以将其中的重复代码提取出来,写成一个函数,然后在需要使用的地方调用即可。比如,可以将以下部分提取出来:
```
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])
```
写成一个名为 `split_list` 的函数,如下所示:
```
def split_list(demand_id_list, node_id_list, split_start, split_end):
new_c1_f = []
new_c1_m = node_id_list[split_start:split_end+1]
new_c1_b = []
for index in range(len(demand_id_list)):
if len(new_c1_f)<split_start:
if node_id_list[index] not in new_c1_m:
new_c1_f.append(node_id_list[index])
else:
if node_id_list[index] not in new_c1_m:
new_c1_b.append(node_id_list[index])
return new_c1_f + new_c1_m + new_c1_b
```
然后在需要使用的地方调用 `split_list` 函数即可,如下所示:
```
new_c1 = split_list(model.demand_id_list, f2.node_id_list, cro1_index, cro2_index)
new_c2 = split_list(model.demand_id_list, f1.node_id_list, cro1_index, cro2_index)
```
这样可以大大降低代码的重复率,让代码更加简洁易懂。
阅读全文