How to Find the Intersection of Multiple Lists within a List in Python?

Barbara Streisand
Release: 2024-10-21 22:14:02
Original
1008 people have browsed it

How to Find the Intersection of Multiple Lists within a List in Python?

Finding the Intersection of Multiple Lists in Python

In Python, determining the intersection of two lists is straightforward using the set.intersection() method. However, the question arises: how do we find the intersection of multiple lists within a list?

Consider the scenario where we have a list of lists, aptly named d, containing three elements a, b, and c, as shown below:

<code class="python">d = [[1, 2, 3, 4], [2, 3, 4], [3, 4, 5, 6, 7]]</code>
Copy after login

To determine the intersection of all three lists, we can leverage Python's set.intersection() method and the map() function. The map() function takes two arguments: a function and an iterable. In this case, we apply the map() function with the set() function to convert each list element in d into a set. The resulting output is a list of sets.

Finally, we utilize the set.intersection() method to compute the intersection of these sets, effectively finding the intersection of all three lists within d.

<code class="python">intersection = set.intersection(*map(set, d))</code>
Copy after login

By executing this code, we obtain the desired intersection:

<code class="python">print(intersection)  # Output: {3, 4}</code>
Copy after login

Therefore, even when dealing with multiple lists within a list, Python provides a concise solution for determining their intersection using the set.intersection() method in conjunction with the map() function.

The above is the detailed content of How to Find the Intersection of Multiple Lists within a List in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!