降低这段代码重复率:def readCSVFile(demand_file, depot_file, model): model['demand_dict'] = {int(row['id']): Demand(id=int(row['id']), x_coord=float(row['x_coord']), y_coord=float(row['y_coord']), demand=float(row['demand']), start_time=float(row['start_time']), end_time=float(row['end_time']), service_time=float(row['service_time'])) for row in csv.DictReader(open(demand_file))} model['demand_id_list'] = list(model['demand_dict'].keys()) model['number_of_demands'] = len(model['demand_id_list']) model['vehicle_dict'] = {row['vehicle_type']: Vehicle(depot_id=row['depot_id'], x_coord=float(row['x_coord']), y_coord=float(row['y_coord']), type=row['vehicle_type'], capacity=float(row['vehicle_capacity']), free_speed=float(row['vehicle_speed']), numbers=float(row['number_of_vehicle']), fixed_cost=float(row['fixed_cost']), variable_cost=float(row['variable_cost']), start_time=float(row['start_time']), end_time=float(row['end_time'])) for row in csv.DictReader(open(depot_file))} model['vehicle_type_list'] = list(model['vehicle_dict'].keys())
时间: 2024-01-20 19:02:47 浏览: 139
可以将相似的代码提取出来,写成一个函数。比如:
```
def readDictFromFile(file_path, key_fn, value_fn):
with open(file_path) as f:
return {key_fn(row): value_fn(row) for row in csv.DictReader(f)}
```
然后就可以用这个函数来读取需求和车辆的字典了,代码如下:
```
model['demand_dict'] = readDictFromFile(demand_file, lambda row: int(row['id']), lambda row: Demand(id=int(row['id']), x_coord=float(row['x_coord']), y_coord=float(row['y_coord']), demand=float(row['demand']), start_time=float(row['start_time']), end_time=float(row['end_time']), service_time=float(row['service_time'])))
model['demand_id_list'] = list(model['demand_dict'].keys())
model['number_of_demands'] = len(model['demand_id_list'])
model['vehicle_dict'] = readDictFromFile(depot_file, lambda row: row['vehicle_type'], lambda row: Vehicle(depot_id=row['depot_id'], x_coord=float(row['x_coord']), y_coord=float(row['y_coord']), type=row['vehicle_type'], capacity=float(row['vehicle_capacity']), free_speed=float(row['vehicle_speed']), numbers=float(row['number_of_vehicle']), fixed_cost=float(row['fixed_cost']), variable_cost=float(row['variable_cost']), start_time=float(row['start_time']), end_time=float(row['end_time'])))
model['vehicle_type_list'] = list(model['vehicle_dict'].keys())
```
阅读全文