Rafael Frinhani Rafael Frinhani - 2 months ago 6
Python Question

Merge lists in specific order

I have a list of lists and i want to merge the lists with an specific order. See example:

id list 0 1 2
[[0], [2, 6, 1, 4], [3, 7, 5]]

Order Resulting List
[1, 0, 2] = [2, 6, 1, 4, 0, 3, 7, 5]
[0, 2, 1] = [0, 3, 7, 5, 2, 6, 1, 4]
[2, 1, 0] = [3, 7, 5, 2, 6, 1, 4, 0]


Someone can suggest a more elegant algorithm that proposed below?

groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[1, 0, 2], [0, 2, 1], [2, 1, 0]]

for order in orders:
LC = []
for i in order:
LC += groups[i]
return LC


Gentlemens, let me explain a bit better what I need:

groups = [[0], [2, 6, 1, 4], [3, 7, 5]]
orders = [[0, 2, 1], [1, 0, 2], [2, 1, 0]] # Order of each group in LC
solutions = [] # I want to put the created LC here
for order in orders:
LC = [] # I need this because a want LCs individualy and not one with all
for i in order: # for each order I pick de index (i) of the group
LC += grupos[i] # and merge then according with index of group
solutions.append([LC])
print(solutions)


i want this (one LC for each order):

[[0, 3, 7, 5, 2, 6, 1, 4], [2, 6, 1, 4, 0, 3, 7, 5], [3, 7, 5, 2, 6, 1, 4, 0]]


and not this:

[0, 3, 7, 5, 2, 6, 1, 4, 2, 6, 1, 4, 0, 3, 7, 5, 3, 7, 5, 2, 6, 1, 4, 0]


The algorithm above works, but a need a another one more elegant and efficient.

Some examples of output:

groups = [[0], [2, 1], [3, 7, 5], [4], [6]]

Order = [1, 0, 2, 3, 4]
LC = [2, 1, 0, 3, 7, 5, 4, 6]

[2, 1, 0, 3, 4]
[3, 7, 5, 2, 1, 0, 4, 6]

[3, 1, 2, 0, 4]
[4, 2, 1, 3, 7, 5, 0, 6]

[4, 1, 2, 3, 0]
[6, 2, 1, 3, 7, 5, 4, 0]

[0, 2, 1, 3, 4]
[0, 3, 7, 5, 2, 1, 4, 6]

[0, 3, 2, 1, 4]
[0, 4, 3, 7, 5, 2, 1, 6]

[0, 4, 2, 3, 1]
[0, 6, 3, 7, 5, 4, 2, 1]

[0, 1, 3, 2, 4]
[0, 2, 1, 4, 3, 7, 5, 6]

[0, 1, 4, 3, 2]
[0, 2, 1, 6, 4, 3, 7, 5]

[0, 1, 2, 4, 3]
[0, 2, 1, 3, 7, 5, 6, 4]

Answer

This solution is basically identical to the one you proposed, but more Python-esque, using a list comprehension.

>>> def merge_lists(desired_order):
...     merged_list = [element for i in desired_order for element in parts[i]]
...     return merged_list
... 
>>> desired_order = orders[0]
>>> merge_lists(desired_order)
[2, 6, 1, 4, 0, 3, 7, 5]