优化这段代码:def readCSVFile(demand_file,depot_file,model): with open(demand_file,'r') as f: demand_reader=csv.DictReader(f) for row in demand_reader: demand = Demand() demand.id = int(row['id']) demand.x_coord = float(row['x_coord']) demand.y_coord = float(row['y_coord']) demand.demand = float(row['demand']) demand.start_time=float(row['start_time']) demand.end_time=float(row['end_time']) demand.service_time=float(row['service_time']) model.demand_dict[demand.id] = demand model.demand_id_list.append(demand.id) model.number_of_demands=len(model.demand_id_list) with open(depot_file, 'r') as f: depot_reader = csv.DictReader(f) for row in depot_reader: vehicle = Vehicle() vehicle.depot_id = row['depot_id'] vehicle.x_coord = float(row['x_coord']) vehicle.y_coord = float(row['y_coord']) vehicle.type = row['vehicle_type'] vehicle.capacity=float(row['vehicle_capacity']) vehicle.free_speed=float(row['vehicle_speed']) vehicle.numbers=float(row['number_of_vehicle']) vehicle.fixed_cost=float(row['fixed_cost']) vehicle.variable_cost=float(row['variable_cost']) vehicle.start_time=float(row['start_time']) vehicle.end_time=float(row['end_time']) model.vehicle_dict[vehicle.type] = vehicle model.vehicle_type_list.append(vehicle.type)
时间: 2024-03-24 18:39:55 浏览: 42
可以使用列表推导式来简化代码:
```
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())
```
这个版本的代码使用了字典推导式和列表推导式,使得代码更加简洁易懂,同时也提高了代码的可读性。
阅读全文