简体   繁体   English

Python中两个嵌套列表的交集

[英]Intersection of two nested lists in 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. 我想用python语言计算两个嵌套列表的交集的长度。 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]

The in operator will test for equality, so different list objects with the same contents be found as expected. in运算符将测试是否相等,因此可以按预期找到具有相同内容的不同列表对象。 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)) . 换句话说,其性能为O(len(list1)*len(list2)) If your lists are long however, it may take more time than you want it to. 但是,如果您的清单很长,可能要花费比您想要的更多的时间。

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. 渐近有效的替代方法是将内部列表转换为tuple s,并将顶级list s转换为set 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: 实际上,您实际上不需要为此编写任何循环,因为mapset类型的&运算符将为您处理所有这一切:

intersection_set = set(map(tuple, list1)) & set(map(tuple, list2))

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: 如果您需要的结果是一个listlist S,你当然可以,转换settuple的背部成listlist S:

intersection_list = list(map(list, intersection_set))

What about using sets in python? 在python中使用集合呢?

>>> set1={(1,2),(2,3),(3,4)}
>>> set2={(1,2),(6,7),(4,5)}
>>> set1 & set2
set([(1, 2)])
>>> len(set1 & set2)
1
import json



list1 = [[1,2], [2,3], [3,4]]
list2 = [[1,2], [6,7], [4,5]]

list1_str = map(json.dumps, list1)
list2_str = map(json.dumps, list2)

output_set_str = set(list1_str) & set(list2_str)

output_list = map(json.loads, output_set_str)

print output_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM