帮我优化这段代码: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-02-07 08:02:24 浏览: 108
depot_tools工具包
可以考虑使用 pandas 库读取 CSV 文件,以提高效率。具体而言,可以使用 pandas.read_csv() 函数读取 CSV 文件,并将其转换为 DataFrame。然后,可以使用 DataFrame.apply() 函数将每一行数据转换为 Demand 或 Vehicle 对象,最后将这些对象添加到 model 中。
下面是示例代码:
```python
import pandas as pd
def readCSVFile(demand_file, depot_file, model):
# 读取需求数据
demand_df = pd.read_csv(demand_file)
demand_df = demand_df.apply(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'])
), axis=1)
model.demand_dict = dict(zip(demand_df['id'], demand_df))
model.demand_id_list = list(demand_df['id'])
model.number_of_demands = len(model.demand_id_list)
# 读取车辆数据
depot_df = pd.read_csv(depot_file)
depot_df = depot_df.apply(lambda row: Vehicle(
depot_id=row['depot_id'],
x_coord=float(row['x_coord']),
y_coord=float(row['y_coord']),
vehicle_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'])
), axis=1)
model.vehicle_dict = dict(zip(depot_df['vehicle_type'], depot_df))
model.vehicle_type_list = list(depot_df['vehicle_type'])
```
在以上代码中,Demand 和 Vehicle 类需要根据具体情况进行实现。另外,需要确保 pandas 库已经安装并导入。
阅读全文