A summary of the methods used by python to calculate the list intersection, and a python Intersection

Source: Internet
Author: User

A summary of the methods used by python to calculate the list intersection, and a python Intersection

This example summarizes the methods used by python to calculate the list intersection. Share it with you for your reference. The specific method is as follows:

The intersection of A and B in A given two sets refers to A set that contains all elements that belong to both A and B, and A set without other elements is called an intersection, the following are examples of how to calculate the list intersection in python for your reference.

Method 1

Traverse b1. If an element also exists in b2, return
Copy codeThe Code is as follows: b1 = [1, 2, 3]
B2 = [2, 3, 4]
B3 = [val for val in b1 if val in b2]
Print b3
The running result is as follows:
Copy codeThe Code is as follows: [2, 3]
Method 2

Converts a list to a set, uses the set operator to obtain the intersection, and then returns the list type.
Copy codeThe Code is as follows: b1 = [1, 2, 3]
B2 = [2, 3, 4]
B3 = list (set (b1) & set (b2 ))
Print b3
The running result is as follows:
Copy codeThe Code is as follows: [2, 3]
Method 3

In the previous example, both lists are simple single-element lists. In another special case, there is a nested type.
Copy codeThe Code is as follows: b1 = [1, 2, 3]
B2 = [[2, 4], [3, 5]
B3 = [filter (lambda x: x in b1, sublist) for sublist in b2]
Print b3
The running result is as follows:
Copy codeThe Code is as follows: [2, 3]

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.