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
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))
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With