Intersection of two nested lists in Python

懵懂的女人 提交于 2019-12-23 02:26:15

问题


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?


回答1:


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. 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.

A more asymptotically efficient alternative approach is to convert the inner lists to tuples and turn the top level lists into sets. 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))

If you need your result to be a list of lists, you can of course, convert the set of tuples back into a list of lists:

intersection_list = list(map(list, intersection_set))



回答2:


What about using sets in python?

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



回答3:


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


来源:https://stackoverflow.com/questions/29462496/intersection-of-two-nested-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!