1

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

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

在输出中,我需要获取它们之间的所有交集:

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

它的算法是什么?

4

4 回答 4

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]]
于 2013-01-09T18:46:42.937 回答
1

您可以使用在 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])
于 2013-01-09T18:43:45.963 回答
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])
于 2013-01-09T18:44:38.190 回答
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]]
于 2013-01-09T18:47:11.347 回答