The goal is to compute the difference between two lists, x and y, resulting in a new list containing elements from x that are not present in y.
To preserve the original order from x, use a list comprehension to check which elements are not in y:
1 |
|
If the order of elements in the resulting list is not important, a set difference can be employed:
1 |
|
To enable the infix x - y syntax for list subtraction, a custom class can be created that overrides the __sub__ method to implement the desired behavior:
1 2 3 |
|
With this class, the subtraction can be performed as follows:
1 2 3 |
|
The above is the detailed content of How to Compute the Difference Between Two Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!