python中有序集合的交集

时间:2013-01-09 18:41:57

标签: python python-3.x

我是python的新手,这就是为什么我正在努力解决我认为非常基本的问题。我有两个清单:

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

在输出上我需要得到它们之间的所有交叉点:

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

算法是什么?

4 个答案:

答案 0 :(得分:7)

您可以将difflib.SequenceMatcher用于此目的

#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]]

答案 1 :(得分:1)

您可以使用支持python

中的交叉点的sets

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])

答案 2 :(得分:1)

使用套装:

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])

答案 3 :(得分:1)

你也可以使用lambda表达式:

>>> 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]]