简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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