Home >Backend Development >Python Tutorial >How to Find the Intersection of Nested Lists in Python?
Intersection of Nested Lists
Determining the intersection of two flat lists is straightforward using set operations or list comprehensions. However, the challenge arises when dealing with nested lists.
Solution:
To find the intersection of nested lists, where both lists contain sublists, you can leverage the intersection method of the set data structure. By utilizing this method, you can extract the common elements between two lists while disregarding the nesting structure.
Here's an example to demonstrate this approach:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63] c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] # Create a set from the flat list s1 = set(c1) # Create a set of sets from the nested list s2 = {set(x) for x in c2} # Find the intersection of the sets c3 = [list(s1.intersection(x)) for x in s2]
In this example, the result c3 will contain the intersection of the nested lists c1 and `c2':
c3 = [[13, 32], [7, 13, 28], [1, 6]]
The above is the detailed content of How to Find the Intersection of Nested Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!