Ordered intersection of two lists in Python

I know in Python, if I have:

list_1 = [1,2,3]
list_2 = [2,3,4]

I can do the following to find the intersection between them:

list(set(list_1) & set(list_2))
# = [2,3]

But there is one problem with this approach: sets do not maintain order, as lists do. Therefore, if I have:

list_1 = [3,2,1]
list_2 = [2,3,4]

I get:

list(set(list_1) & set(list_2))
# = [2,3]

although I would prefer to have order from the first list, i.e.:

# = [3,2]

Is there an alternative intersection method that preserves the resulting “intersection set” in the same order as the first list?

+4
source share
2 answers
set_2 = frozenset(list_2)
intersection = [x for x in list_1 if x in set_2]

set frozenset , , . , , , n * m : [x for x in list_1 if x in list_2]. set - O (1) O (n) .

+9

:

l1 = [3, 2, 1]
l2 = [2, 3, 4]
sorted(set(l1) & set(l2), key = l1.index)

:

[3, 2]
+2

Source: https://habr.com/ru/post/1539670/


All Articles