How to Find the Intersection of a Flat List and a Nested List in Python?

Barbara Streisand
Release: 2024-11-25 22:00:14
Original
249 people have browsed it

How to Find the Intersection of a Flat List and a Nested List in Python?

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]]
Copy after login

Here, the desired outcome is:

c3 = [[13, 32], [7, 13, 28], [1, 6]]
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template