python中有序集合的交集

2024-04-27 02:55:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

算法是什么?在


Tags: 算法新手交点pr2
3条回答

您可以为此使用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]]

使用集:

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

您可以使用支持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])

相关问题 更多 >