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.