Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply the order of list to another lists

I have a list, with a specific order:

L = [1, 2, 5, 8, 3]

And some sub lists with elements of the main list, but with an different order:

L1 = [5, 3, 1]
L2 = [8, 1, 5]

How can I apply the order of L to L1 and L2?

For example, the correct order after the processing should be:

 L1 = [1, 5, 3]
 L2 = [1, 5, 8]

I am trying something like this, but I am struggling how to set the new list with the correct order.

new_L1 = []
for i in L1:
   if i in L: 
      print L.index(i) #get the order in L
like image 902
anvd Avatar asked Feb 12 '16 17:02

anvd


2 Answers

Looks like you just want to sort L1 and L2 according to the index where the value falls in L.

L = [1, 2, 5, 8, 3]

L1 = [5, 3, 1]
L2 = [8, 1, 5]

L1.sort(key = lambda x: L.index(x))
L2.sort(key = lambda x: L.index(x))
like image 92
Garrett R Avatar answered Sep 22 '22 00:09

Garrett R


Here is another way you can sort using List comprehensions:

>>> L = [1, 2, 5, 8, 3]
>>> 
>>> L1 = [5, 3, 1]
>>> L2 = [8, 1, 5]
>>> 
>>> L1 = [i for i in L if i in L1]
>>> L2 = [i for i in L if i in L2]
>>> 
>>> L1
[1, 5, 3]
>>> L2
[1, 5, 8]
like image 32
karthikr Avatar answered Sep 23 '22 00:09

karthikr