python中有序集合的交集
我对python还不熟悉,这就是为什么我在思考一个非常基本的问题。我有两份清单:python中有序集合的交集,python,python-3.x,Python,Python 3.x,我对python还不熟悉,这就是为什么我在思考一个非常基本的问题。我有两份清单: a = [0, 1, 2, 3, 4, 5, 6, 7] b = [1, 2, 5, 6] 在输出上,我需要得到它们之间的所有交点: c = [[1, 2], [5, 6]] 算法是什么?您可以使用python中支持交叉点的 s.交叉点(t)s&t新集合,具有s和t共有的元素 a = {0, 1, 2, 3, 4, 5, 6, 7} b = {1, 2, 5, 6} a.intersection(b) set(
a = [0, 1, 2, 3, 4, 5, 6, 7]
b = [1, 2, 5, 6]
在输出上,我需要得到它们之间的所有交点:
c = [[1, 2], [5, 6]]
算法是什么?您可以使用python中支持交叉点的
s.交叉点(t)s&t新集合,具有s和t共有的元素
a = {0, 1, 2, 3, 4, 5, 6, 7}
b = {1, 2, 5, 6}
a.intersection(b)
set([1, 2, 5, 6])
您可以使用python中支持交叉点的
s.交叉点(t)s&t新集合,具有s和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])
使用集合:
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])
您可以为此目的使用
#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]]
您可以为此目的使用
#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]]
您还可以使用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]]
您还可以使用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]]
你的输出不是应该是
[1,2,5,6]
吗?通过你的c
输出示例,我猜你想要作为交点存在的范围的极值,对吗?如果a 3也包含在b
中,那么您的预期输出是什么?如果b中包含了3,我会期望:c=[[1,2,3],[5,6]]您的输出不应该是[1,2,5,6]
?我通过您的c
输出示例猜测,您希望范围的极值作为交点存在,对吗?如果a 3也包含在b
中,那么您的预期输出是什么?如果b中包含了3,我会期望:c=[[1,2,3],[5,6]]Thx很多,这正是我所期待的简单和出色,因为这将在排序集和所有排序集上都有效,即使这些未排序。。。尊重顺序!Thx很多,正是我所期待的简单和卓越,因为这将对排序集和所有排序集都有效,即使这些没有排序。。。尊重顺序!这适用于排序集,但可能不适用于所有排序集,对吗?交集并不意味着顺序。同意,尽管问题是关于列表而不是集合。但你还是有一个好的观点。这对排序集是有效的,但对所有排序集可能都不适用,对吗?交集并不意味着顺序。同意,尽管问题是关于列表而不是集合。但无论如何,你有一个很好的观点。