Python sums up the methods for the intersection of lists

  • 2020-04-02 14:22:39
  • OfStack

This example summarizes python's methods for finding the intersection of lists. Share with you for your reference. Specific methods are as follows:

Intersection for the given two sets A and set B, the intersection refers to the set containing all the elements that belong to both A and B, and no other elements are called intersection, the following is A few python list intersection examples for your reference.

Method 1

Traversing b1, returns if an element also exists in b2

b1=[1,2,3]
b2=[2,3,4]
b3 = [val for val in b1 if val in b2]
print b3

The results are as follows
[2, 3]

Method 2

Convert a list to a collection, use the set operator to figure out the intersection, and then convert back to the list type
b1=[1,2,3]
b2=[2,3,4]
b3=list(set(b1) & set(b2))
print b3

The results are as follows
The same code at the page code block index 1
Methods 3

In the previous example, both lists were simple single-element lists, and in a more unusual case, nested

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 are as follows
The same code at the page code block index 1

I hope this article has helped you with your Python programming.


Related articles: