Python中两个嵌套列表的交集 [英] Intersection of two nested lists in Python
问题描述
我对嵌套列表有疑问.我想用python语言计算两个嵌套列表的交集的长度.我的列表组成如下:
I've a problem with the nested lists. I want to compute the lenght of the intersection of two nested lists with the python language. My lists are composed as follows:
list1 = [[1,2], [2,3], [3,4]]
list2 = [[1,2], [6,7], [4,5]]
output_list = [[1,2]]
如何计算两个列表的交集?
How can i compute the intersection of the two lists?
推荐答案
我认为有两种合理的方法可以解决此问题.
I think there are two reasonable approaches to solving this issue.
如果顶层列表中没有太多项目,则可以简单地检查其中一个子列表中的每个子列表是否存在:
If you don't have very many items in your top level lists, you can simply check if each sub-list in one of them is present in the other:
intersection = [inner_list for inner in list1 if inner_list in list2]
in
运算符将测试是否相等,因此可以按预期找到内容相同的不同列表对象.但是,这不是很有效,因为列表成员资格测试必须遍历所有子列表.换句话说,其性能为O(len(list1)*len(list2))
.但是,如果您的列表很长,则可能要花费比您想要的更多的时间.
The in
operator will test for equality, so different list objects with the same contents be found as expected. This is not very efficient however, since a list membership test has to iterate over all of the sublists. In other words, its performance is O(len(list1)*len(list2))
. If your lists are long however, it may take more time than you want it to.
一种渐近有效的替代方法是将内部列表转换为tuple
s并将顶级list
s转换为set
s.您实际上不需要为此编写任何循环,因为map
和set
类型的&
运算符将为您处理所有这些事情:
A more asymptotically efficient alternative approach is to convert the inner lists to tuple
s and turn the top level list
s into set
s. You don't actually need to write any loops yourself for this, as map
and the set
type's &
operator will take care of it all for you:
intersection_set = set(map(tuple, list1)) & set(map(tuple, list2))
如果需要将结果作为list
的list
,则可以将tuple
s的set
转换回list
s的list
:
If you need your result to be a list
of list
s, you can of course, convert the set
of tuple
s back into a list
of list
s:
intersection_list = list(map(list, intersection_set))
这篇关于Python中两个嵌套列表的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!