优化这段代码:降低这段代码重复率: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 11:02:47 浏览: 53
可以将其中的一些重复代码提取出来,写成函数或者变量。比如:
```
def parse_demand_row(row):
return 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']))
def parse_vehicle_row(row):
return 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']))
demand_dict = {int(row['id']): parse_demand_row(row) for row in csv.DictReader(open(demand_file))}
demand_id_list = list(demand_dict.keys())
number_of_demands = len(demand_id_list)
vehicle_dict = {row['vehicle_type']: parse_vehicle_row(row) for row in csv.DictReader(open(depot_file))}
vehicle_type_list = list(vehicle_dict.keys())
model['demand_dict'] = demand_dict
model['demand_id_list'] = demand_id_list
model['number_of_demands'] = number_of_demands
model['vehicle_dict'] = vehicle_dict
model['vehicle_type_list'] = vehicle_type_list
```
这样可以大大降低代码的重复率,同时也方便了代码的维护和修改。
阅读全文