我想从下面的元组列表中创建一个动态元组列表:
Optimal_Route = [(1, 5), (2, 3), (3, 1), (4, 2), (5, 4)]
。
我的最终目标是拥有如下内容:
路线= [[(1,5),(5,4),(4,2)],[(2,3),(3,1)]]
我希望这个基于“depotList”和“affectedAreaList”的“路由”元组列表是动态的。下面是我为此任务编写的代码,但我正在努力使其高效和动态。我会对此有所帮助。感谢
Optimal_Route = [(1, 5), (2, 3), (3, 1), (4, 2), (5, 4)]
Route = []
depotList = [1,2]
affectedAreaList = [3,4,5]
count = 0
while count < len(Optimal_Route):
next_route = True
cur_route = []
for tup in Optimal_Route:
if tup[0] in depotList and next_route == True:
cur_route.append(tup)
b = tup[1]
for tup in Optimal_Route:
if tup[0] == b:
cur_route.append(tup)
if not tup[1] in depotList:
next_route = False
b = tup[1]
print b
for tup in Optimal_Route:
if tup[0] == b:
cur_route.append(tup)
Route.append(cur_route)
next_route = True
cur_route = []
count +=1
答案 0 :(得分:0)
根据您提供的数据,使用字典而不是处理元组:
Optimal_Route = [(1, 5), (2, 3), (3, 1), (4, 2), (5, 4)]
Route = []
depotList = [1,2]
affectedAreaList = [3,4,5]
legs = dict(Optimal_Route)
routes = {}
for start in depotList :
place = start
routes[start] = []
end_places = [ i for i in depotList if i != start ]
while place not in end_places :
routes[start].append((place,legs[place]))
place = legs[place]
for i in routes.keys() :
print(i,routes[i])
print([ i for i in routes.values()])