Nested List Intersection
You might encounter situations where you need to find the intersection of nested lists, unlike the basic flattening of two flat lists. For instance, consider the following scenario:
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]]
Here, the desired outcome is:
c3 = [[13, 32], [7, 13, 28], [1, 6]]
To achieve this, you can leverage Python's set intersection capability.
The set data structure in Python naturally includes an intersection function. You don't need to define your own intersection method. For example:
set(c1).intersection(c2)
This code snippet will return a set containing the intersection of elements between c1 and c2. To obtain the desired nested list format, you can perform additional processing or convert the set back into a list using the list() function.
The above is the detailed content of How to Find the Intersection of a Flat List and a Nested List in Python?. For more information, please follow other related articles on the PHP Chinese website!