[英]Intersection of ordered collection in python
我是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中的交集的集
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])
使用集:
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])
您还可以为此使用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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.