Reputation: 171
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
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
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
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