降低这段代码重复率: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 17:39:55 浏览: 104
可以将读取 CSV 文件的代码提取出来,封装成一个函数,这样可以减少代码的重复率。可以这样来实现:
```
def readCSV(csv_file, model, obj_type):
with open(csv_file, 'r') as f:
csv_reader = csv.DictReader(f)
for row in csv_reader:
obj = obj_type()
for key, value in row.items():
setattr(obj, key, float(value) if value.replace('.', '', 1).isdigit() else value)
obj_id = getattr(obj, 'id', None)
if obj_id is not None:
model[obj_id] = obj
model['{}_id_list'.format(type(obj).__name__.lower())].append(obj_id)
model['number_of_{}s'.format(type(obj).__name__.lower())] = len(model['{}_id_list'.format(type(obj).__name__.lower())])
```
然后就可以这样来调用这个函数:
```
model = {'demand_dict': {}, 'vehicle_dict': {}}
readCSV(demand_file, model['demand_dict'], Demand)
readCSV(depot_file, model['vehicle_dict'], Vehicle)
```
这样就可以将原来的代码大大简化,减少重复率,同时可以让代码更加简洁易懂。
阅读全文