Search code examples
pythonarrayssortingdictionaryreorderlist

How to reorder list based off of another list's ordering?


I have one list that in a specific order let's say something like ['hello', 'I', 'like', 'sunshine'] and I have a second list that contains all of the first list and some extra elements ['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']. This is sort of a nonsensical example, but essentially the main idea is the first list is a subset of the second, but the elements from the first do not appear in the same order that they originally appeared in (they are scrambled up in the second list). I want to reorder the second list so it has the elements from the first list in the beginning in the original order, and then has its unique elements. Therefore, this reordered second list would like ['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows'].

Hopefully this makes sense. I actually don't care how the unique elements appear in the final reordered list (they can be rearranged for all I care but it is crucial the elements from the first list appear in the beginning and maintain original order). How do I achieve this? I am a bit lost.


Solution

  • Here's a nice one-liner solution:

    a = ['hello', 'I', 'like', 'sunshine']
    b = ['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']
    
    b = sorted(b, key=lambda x: a.index(x) if x in a else len(a) + b.index(x))
    # b = ['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows']