Skip to main content
 首页 » 编程设计

python之python中有序集合的交集

2025年05月04日21zdz8207

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

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

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

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

它的算法是什么?

请您参考如下方法:

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