Sort a list according to another list, with uneven length

Viewed 462

Let's say I have two lists, l1 and l2:

l1 = [1,9,6,8,3]
l2 = [8,1]

The list l2 will be sorted according to the ordering of list l1, so in this case:

l2_reordered = [1,8]

Note: List l2 will always have 2 items which have a different value.

I can think of a naive loop approach to doing this, but that is going to be really inefficient. What is a pythonic and efficient way of doing this?

3 Answers

Here's a fast solution. First build a dict mapping values to indices:

d = {v:i for i, v in enumerate(l1)}

Then use it to obtain sort keys:

r = sorted(l2, key=lambda v: d[v])

Creating d is O(len(l1)), and the sort is O(len(l2)*log(len(l2))).

SORT_ORDER = {_: l1.index(_) for _ in l1}
l2.sort(key=lambda _: SORT_ORDER[_])

Idea from: here

You can traverse l1 while matching it with l2 elements. Whenever you find an element you can mark that index of l1 or maybe store that index in a new list l3. Now in the end you can sort the l3 list based on index numbers.

for ele in l2:
   l3.append(l1.index(ele))
l3.sort()
i=0
for ele in l3:
   l2[i]=l1[ele]
   i+=1

The above code takes in all the values from l2, marks their index numbers in l1.Then we sort all the index numbers and put the sorted values in l2. Hope this can help a little.

Related