Python Find list intersection method Rollup _python

Source: Internet
Author: User

The example in this article summarizes the method by which Python asks for a list intersection. Share to everyone for your reference. The specific methods are as follows:

The intersection of a given set of two sets A and set B is the one that contains all elements that belong to both A and B, and no other element is called the intersection, and here are a few examples of Python's list intersection for your reference.

Method 1

traversing B1, if an element also exists in B2, returns

Copy Code code as follows:
b1=[1,2,3]
b2=[2,3,4]
B3 = [Val for Val in B1 if Val in B2]
Print B3

The results of the operation are as follows
Copy Code code as follows:
[2, 3]

Method 2

Converts the list to a set, uses the set operator to find the intersection, and then converts back to the list type
Copy Code code as follows:
b1=[1,2,3]
b2=[2,3,4]
B3=list (Set (B1) & Set (B2))
Print B3

The results of the operation are as follows
Copy Code code as follows:
[2, 3]

Method 3

In the previous example, the two list is a simple list of single elements, and there is a special case where there are nested types of

Copy Code code 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 results of the operation are as follows
Copy Code code as follows:
[2, 3]

I hope this article will help you with your Python programming.

Related Article

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.