I have a list A
and list B
, I want to get common elements from the two lists but want when I get the common elements they should maintain the order of List A
.
First I started with converting them in to set and taking the intersection but that had the problem of maintaining the order.
common = list(set(A).intersection(set(B)))
so I decided to do list comprehension:
common = [i for i in A if i in B]
I am getting
IndexError: too many indices for array
Lists Are Ordered It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list's lifetime.
Unlike lists, ordinary sets do not preserve the order in which we insert the elements. This is because the elements in a set are usually not stored in the order in which they appear.
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists.
As a general answer for such problems You can use sorted
function with lambda x:A.index(x)
as its key that 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 use set(B)
for intersection.
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 that raised the IndexError
.
You can speedup membership tests by making a set
from B
:
set_b = set(B)
common = [i for i in A if i in set_b]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With