Python maintains order in intersecting lists

I have a list A

and a list B

, I want to get the common elements from these two lists, but I want when I get the common elements, they must maintain the order of the List A

.

I first started by converting them to set and take the intersection, but it had an order preservation problem.

common = list(set(A).intersection(set(B)))

      

so I decided to do a correspondence:

common = [i for i in A if i in B]

      

I get

IndexError: too many indices for array

      

+3


source to share


2 answers


As a general answer for problems like this, you can use the sorted

c function lambda x:A.index(x)

as your key, which will sort the result based on the order of list A:

>>> common = sorted(set(A).intersection(B) ,key=lambda x:A.index(x))

      



Also note that you don't need to use set(B)

for intersection.

+3


source


Your code ( common = [i for i in A if i in B]

) works just fine. Perhaps what you wrote in your question was not the exact code you raised IndexError

.

You can speed up membership testing by doing set

from B

:



set_b = set(B)
common = [i for i in A if i in set_b]

      

+2


source







All Articles