gpt4 book ai didi

python - python中有序集合的交集

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:40 27 4
gpt4 key购买 nike

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

关于python - python中有序集合的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14244202/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com