Python3 sort a list based on another list when the lists are uneven in length

Viewed 27

I have two lists:

list1 = ["a","e","d","c","f","g"]
list2 = ["a","c","d","f"]

In this the list1 cannot be sorted and should be retained as is. I am trying to sort the list2 exactly in the same order as list1 and get the missing values from list1 that exists between the first and last value of list2.

For example, if I sort list2 as according to list1using the following code,

list2 = [x for _, x in sorted(zip(list1,list2))]

I get the following index based sorted list:

list2 = ['a', 'f', 'd', 'c']

However the desired output is

list2 = ['a','d','c','f']

How can I sort the list2 according to the list1 taking the literal sequence of elements and not the index position based sorting.

1 Answers

It might not be the most efficient, and it doesn't cope with duplicates, but the following list comprehension should do what you want:

list1 = ["a","e","d","c","f","g"]
list2 = ["a","c","d","f"]
print([x for x in list1 if x in list2])
['a', 'd', 'c', 'f']

It walks list1, using the item if it is found in list2.

Related