I have 2 lists of strings
List1 = [["Hey there"], ["hi"], ["hello"]]
List2 = [["hi"], ["hello"]]
Is there a O(n) way to remove elements of List2
from List1
?
Desired output = [["Hey there"]]
You can do this with two O(n) steps:
List2_set = set(map(tuple, List2))
List1_filtered = [row for row in List1 if tuple(row) not in List2_set]
Convert the list of items to exclude to a set
of tuples
set
is required because checking membership for sets is O(1) instead of O(n) tuple
is required for set
items instead of list
, because tuple
is hashable Check membership for each element of List1
set
collection uses a hash table to allow O(1) membership testing The total then is O(n) + O(n) => O(n), that is, the performance is linear with number of total elements of List1
+ List2
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.