Common elements between two lists and preserving the order of elements in the two lists
list, python
Solution
list1 = ['a', 'e', 't', 'b', 'c']
list2 = ['e', 'b', 'a', 'c', 'n', 's']
weights = defaultdict(int)
for i, e in enumerate(list1):
weights[e] += i
for i, e in enumerate(list2):
weights[e] += i
>>> result = sorted(set(list1) & set(list2), key=lambda i: weights[i])
>>> result
['e', 'a', 'b', 'c']
Problem
I have two lists `list1` and `list2`. I've found on stackoverflow a very simple method to get the common elements in this two lists as follows `result = list(set(list1) & set(list2))`. Unfortunately, with this, the order of elements in the resulting list, is not preserved. For instance: ``` list1 = ['a', 'e', 't', 'b', 'c'] list2 = ['e', 'b', 'a', 'c', 'n', 's'] ``` I want the result (common elements) to be `['e', 'a', 'b', 'c']` in this order. Because, for instance, 'e' is in list1 and in list2 and is in position 2 in list1 and position 1 in list2, while 'a' is in list1 and in list2 and is in position 1 in list1 and position 3 in list2, so 'e' is before 'a' since 2+1 < 1+3. So, is there any simple way to have the common elements between two lists and preserving the order of elements ?