Python's way of finding the difference intersection and union of two lists

  • 2020-04-02 14:20:21
  • OfStack

This article illustrates the Python method of finding the difference set, intersection and union of two lists. Share with you for your reference. The details are as follows:

A list is a difference set, an intersection, a union between two arrays, something you learned in elementary school math, and I'm going to analyze it in the form of an example.

One, two list difference sets

If there are the following two arrays:
A = [1, 2, 3]
B = [2, 3]
The desired result is [1]
Here are three implementations:
1. The normal way

ret = []
for i in a:
    if i not in b:
        ret.append(i)

2. The condensed version

ret = [ i for i in a if i not in b ]

3. Another version

ret = list(set(a) ^ set(b))

Individuals prefer the third implementation

Get the union of two lists
 

print list(set(a).union(set(b)))

Get the difference set of two lists

print list(set(b).difference(set(a))) # b There is, a Not found in 

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


Related articles: