Introduction to list subtraction in Python and python Subtraction
Problem description:Suppose I have two lists,
One is list1, list1 = [1, 2, 3, 4, 5]
One is list2, list2 = [1, 4, 5]
How can we get a new list, list3,
List3 includes all elements in list1 that are not in list2.
That is, list3 = list1-list2
Solution:We can use the set operation.
List3 = list (set (list1)-set (list2 ))
The set operation converts a list into a set.
Suppose: list_t = [1, 2, 3, 1]
So: list (set (list_t) = [1, 2, 3]
Yes, duplicate items will be deleted.
Other solutions:List3 = [I for I in list1 if I not in list2] # list parts
This writing is also intuitive.
However, when the list is large, there is no set method.
Additional knowledge:A = [[I, j] for I in range (2) for j in range (3)]
This is very similar to other solutions,
All are judged and calculated in.
It is very convenient, at least more convenient and faster than the following:
A = []
For I in range (2 ):
For j in range (3 ):
A. append ([I, j])
Some problems:If list_tmp = [[1, 2], [2, 3]
That is, the list is not composed of independent elements, but a list,
Set (list_tmp) may cause problems.
Also research:Hash Function