The implementation of list subtraction in Python is described
- 2020-04-02 14:29:51
- OfStack
Problem description: So let's say I have two lists like this,
One is list1, list1 = [1, 2, 3, 4, 5]
One is list2, list2 = [1, 4, 5]
How do we get a new list, list3,
List3 contains all the elements in list1 that do not appear in list2.
List3 = list1 and list2
Solutions:
We can use set operations
List3 = list(set(list1) wok (list2))
The set operation converts a list into a collection.
Suppose: list_t = [1, 2, 3, 1]
Then: list(set(list_t)) = [1, 2, 3]
Yes, duplicate items will be deleted.
Other options:
List3 = [I for I in list1 if I not in list2]
# can be used for list sharding
It's also intuitive to write it this way.
But when the list is large, it's not as fast as the set method.
Additional knowledge:
A = [[I,j] for I in range(2) for j in range(3)]
This is very similar to the other plan,
It's all judgment and calculation in [].
It feels convenient, at least more convenient and faster than the following:
A = []
For I in range (2) :
For j in range (3) :
A.a ppend ([I, j])
Some questions:
If list_tmp = [[1,2],[2,3]]
So instead of having individual elements in a list, we have a list,
Then the set(list_tmp) will go wrong.
To study: The hash function