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
source to share
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.
source to share