orsi
orsi

Reputation: 171

Intersection of ordered collection in python

I am new to python, that's why I am struggling with pretty basic question I think. I have two lists:

a = [0, 1, 2, 3, 4, 5, 6, 7]
b = [1, 2, 5, 6]

On the output I need to get all the intersections between them:

c = [[1, 2], [5, 6]]

What's the algorithm for that?

Upvotes: 1

Views: 752

Answers (4)

Hunter McMillen
Hunter McMillen

Reputation: 61540

You could also use a lambda expression for this:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7]
>>> b = [1, 2, 5, 6]
>>> intersect = filter(lambda x: x in a, b)
>>> intersect
[[1, 2, 5, 6]]

Upvotes: 1

Abhijit
Abhijit

Reputation: 63767

You can use difflib.SequenceMatcher for this purpose

#Returns a set of matches from the given list. Its a tuple, containing
#the match location of both the Sequence followed by the size
matches = SequenceMatcher(None, a , b).get_matching_blocks()[:-1]
#Now its straight forward, just extract the info and represent in the manner
#that suits you
[a[e.a: e.a + e.size] for e in matches]
[[1, 2], [5, 6]]

Upvotes: 7

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251116

use sets:

In [1]: a = [0, 1, 2, 3, 4, 5, 6, 7]

In [2]: b = [1, 2, 5, 6]

In [4]: set(a) & set(b)

Out[4]: set([1, 2, 5, 6])

Upvotes: 1

dm03514
dm03514

Reputation: 55972

You could use sets which supports intersections in python

s.intersection(t) s & t new set with elements common to s and t

a = {0, 1, 2, 3, 4, 5, 6, 7}
b = {1, 2, 5, 6}
a.intersection(b)
set([1, 2, 5, 6])

Upvotes: 1

Related Questions