I have a routes list like this:
routes=
[[(0, 1), (1, 6), (6, 7), (7, 10), (10, 9), (9, 0)],
[(0, 2), (2, 3), (3, 4), (4, 5), (5, 0)],
[(0, 8), (8, 0)]]
Route 1 is from 0 to 1 to 6 to 7 and so on .... how can i transform this list into a list like this:
routes_new= [[0, 1, 6, 7, 10, 9, 0], [0, 2, 3, 4, 5, 0],[0,8,0]]
Thanks a lot!
CodePudding user response:
Assuming you are looking for cycles here, which seems to be the case, a simple way to achieve what you want is using NetworkX's nx.simple_cycles
. This does not require for the edges to be ordered.
import networkx as nx
routes= [[(0, 1), (1, 6), (6, 7), (7, 10), (10, 9), (9, 0)],
[(0, 2), (2, 3), (3, 4), (4, 5), (5, 0)],
[(0, 8), (8, 0)]]
paths = []
for route in routes:
G = nx.from_edgelist(route, create_using=nx.DiGraph)
paths.append(list(nx.simple_cycles(G)))
paths
# [[[0, 1, 6, 7, 10, 9]], [[0, 2, 3, 4, 5]], [[0, 8]]]
If there can be multiple cycles in each route, check other functions in the cycle module, like nx.find_cycle
, which allow you to specify an origin.
CodePudding user response:
A simple list comprehension can help you flatten your lists:
routes_new = [[t[0] for t in l] [l[-1][1]] for l in routes]
NB. this is assuming the edges are in order and linked. No check is performed. If this is not the case, please provide such an example.
output:
[[0, 1, 6, 7, 10, 9, 0], [0, 2, 3, 4, 5, 0], [0, 8, 0]]
CodePudding user response:
You can just take the first number of each tuple and add the very last one for each route :
routes_new = [[val[0] for val in route] [route[-1][-1]] for route in routes]