Home > Net >  Transform a List into 3 Lists
Transform a List into 3 Lists

Time:08-25

get_plan= 
[('Depot', 'Addr_3'),
  ('Addr_3', 'Addr_4'),
  ('Addr_4', 'Depot'),
  ('Depot', 'Addr_1'),
  ('Addr_1', 'Addr_2'),
  ('Addr_2', 'Depot'),
  ('Depot', 'Addr_5'),
  ('Addr_5', 'Addr_6'),
  ('Addr_6', 'Depot')]

How can I transform this plan into a route list like this ( a Solution that every route ends at the depot and a new one begins at the depot)

route_list= 
[[('Depot', 'Addr_3'),
  ('Addr_3', 'Addr_4'),
  ('Addr_4', 'Depot'),]
  [('Depot', 'Addr_1'),
  ('Addr_1', 'Addr_2'),
  ('Addr_2', 'Depot'),]
  [('Depot', 'Addr_5'),
  ('Addr_5', 'Addr_6'),
  ('Addr_6', 'Depot')]]

I need it in a general way.

Thanks a lot!!!

CodePudding user response:

Assuming the input data is correct and there is no check to be made, use a simple loop.

Relying on the end of route:

route_list = []
tmp = []
for t in get_plan:
    tmp.append(t)
    if t[1] == 'Depot':
        route_list.append(tmp)
        tmp = []

Relying on the start of route

route_list = []
tmp = []
for t in get_plan:
    if t[0] == 'Depot':
        if tmp:
            route_list.append(tmp)
        tmp = [t]
    else:
        tmp.append(t)
route_list.append(tmp)

output:

[[('Depot', 'Addr_3'), ('Addr_3', 'Addr_4'), ('Addr_4', 'Depot')],
 [('Depot', 'Addr_1'), ('Addr_1', 'Addr_2'), ('Addr_2', 'Depot')],
 [('Depot', 'Addr_5'), ('Addr_5', 'Addr_6'), ('Addr_6', 'Depot')]]

CodePudding user response:

You can use split_before from more_itertools

from more_itertools import split_before

list(split_before(get_plan, lambda x: x[0] == 'Depot'))

CodePudding user response:

You can achieve this using numpy like this.

import numpy as np

get_plan = [('Depot', 'Addr_3'),
            ('Addr_3', 'Addr_4'),
            ('Addr_4', 'Depot'),
            ('Depot', 'Addr_1'),
            ('Addr_1', 'Addr_2'),
            ('Addr_2', 'Depot'),
            ('Depot', 'Addr_5'),
            ('Addr_5', 'Addr_6'),
            ('Addr_6', 'Depot')]

# create a numpy array
np_arr = np.array(get_plan)
# Find the indices on which to split the array
indices, = np.nonzero(np_arr[:, 0] == "Depot")
# Split the array
route_list = [sub.tolist() for sub in np.split(np_arr, indices) if sub.size]
print(route_list)

Output:

[[['Depot', 'Addr_3'], ['Addr_3', 'Addr_4'], ['Addr_4', 'Depot']], 
[['Depot', 'Addr_1'], ['Addr_1', 'Addr_2'], ['Addr_2', 'Depot']],
[['Depot', 'Addr_5'], ['Addr_5', 'Addr_6'], ['Addr_6', 'Depot']]]

If you want tuples not the list, you can replace the sub.tolist() with list(map(tuple, sub))

route_list = [list(map(tuple, sub)) for sub in np.splite(np_arr, indices) if sub.size]

output:

[[('Depot', 'Addr_3'), ('Addr_3', 'Addr_4'), ('Addr_4', 'Depot')], 
[('Depot', 'Addr_1'), ('Addr_1', 'Addr_2'), ('Addr_2', 'Depot')], 
[('Depot', 'Addr_5'), ('Addr_5', 'Addr_6'), ('Addr_6', 'Depot')]]
  • Related