Given two different lists which share elements in common and have different size, how to reorder the second list based on the order of the elements of the first one? For example:
For:
a = ['a', 'b', 'e', 'z', 'f']
b = ['a', 'f', 'b', 'z', 'g', 'h']
How to reorder list b into:
['a', 'b', 'z', 'f', 'g', 'h']
For:
a = ['a', 'c', 'j', 'r' , 'p']
b = ['b', 'c', 'a']
How to reorder list b into:
['a', 'c', 'b']
So far I tried to:
[x for y, x in sorted(zip(a, b))]
However, I dont understand how to control the fact that the lists have different size. How could I reorder the second list based on the above restrictions?
You can provide a key function to sort based on the index.
a = ['a', 'b', 'e', 'z', 'f']
b = ['a', 'f', 'b', 'z', 'g', 'h']
from math import inf
res = sorted(b, key=lambda x: a.index(x) if x in a else inf)
print(res)