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:
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:
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:
I hope this article will help you with your Python programming.