There is conditions when we need to matching two of big list of data which it’s called “intersection”.
Python is a great language which provide many ways to achieve solution of this problem. First, we have the list datasets:
1 2 | first = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] second = [2, 4, 5, 8, 9] |
Now the solutions:
1. List comprehension
List comprehension provide concise way to doing map(), filter() or reduce().
1 | [x for x in first if x in second] |
2. Joining sets
We can doing intersection by joining two sets together
1 | sorted(list(set(first) & set(second))) |
3. Sets intersection
1 | sorted(list(set(first).intersection(second))) |
All will give the same results:
1 | [2, 4, 5, 8, 9] |