我正在尝试使用networkx库绘制卡车路线优化的结果。首先,我需要准备数据,但目前遇到了困难。
这是初始数据的一个小例子:
| 车辆 | 路线 |
| ---- | -------------- |
| 0 | [0,3](V0) |
| 1 | [3,0](V0) |
| 2 | [0,3](V1) |
| 3 | [0,8](V1) |
| 4 | [2,0](V1) |
| 5 | [3,2](V1) |
| 6 | [8,0](V1) |
这里有两辆卡车:V0和V1。V0的路线是0到3再到0。而V1有两条路线:0到8再到0以及0到3再到2再到0。
每个行程都必须从节点0开始并在0结束。
我需要解决两个问题:
- 对于每辆卡车(V0、V1),在给定列表中找到所有以0开始并以0结束的行程。
- 行程流不能有中断:每个子行程的终点[0,8]必须是下一个子行程[8,0]的起点。
最终结果应为:
{'V0': [0,3,0], 'V1': [[0,3,2,0], [0,8,0]]}
我已经编写了一段代码,但是它并没有得到我想要的结果:
tours = {'V0': ['0,3', '3,0'], 'V1': ['0,3', '0,8', '2,0', '3,2', '8,0']}
# 定义将字符串转换为列表的函数
def convert_to_list(s):
return list(map(int, s.split(',')))
# 定义处理'tours'字典中每个值的函数
def process_value(value):
result = []
current_list = []
for pair in value:
pair_list = convert_to_list(pair)
if not current_list or pair_list[0] == 0:
current_list.extend(pair_list)
elif pair_list[1] == 0:
current_list.append(pair_list[0])
current_list.append(0)
result.append(current_list)
current_list = [0]
else:
current_list.append(pair_list[0])
if current_list:
current_list.append(0)
result.append(current_list)
return result
# 创建处理后的'tours1'字典
tours1 = {key: process_value(value) for key, value in tours.items()}
# 打印结果
print(tours1)
输出结果:
{'V0': [[0, 3, 3, 0], [0, 0]], 'V1': [[0, 3, 0, 8, 2, 0], [0, 3, 8, 0], [0, 0]]}
有没有改进这段代码的想法或解决方案?非常感谢!