[英]How to remove set of lists from a list of lists
I have 2 lists of strings我有 2 个字符串列表
List1 = [["Hey there"], ["hi"], ["hello"]]
List2 = [["hi"], ["hello"]]
Is there a O(n) way to remove elements of List2
from List1
?是否有一种 O(n) 方法可以从List1
中删除List2
的元素?
Desired output = [["Hey there"]]
所需的 output = [["Hey there"]]
You can do this with two O(n) steps:您可以通过两个 O(n) 步骤来做到这一点:
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
tuples
set
is required because checking membership for sets is O(1) instead of O(n) set
是必需的,因为检查集合的成员资格是 O(1) 而不是 O(n)tuple
is required for set
items instead of list
, because tuple
is hashable set
项而不是list
需要tuple
tuple
可散列的Check membership for each element of List1
检查List1
的每个元素的成员资格
set
collection uses a hash table to allow O(1) membership testing set
集合使用 hash 表来允许 O(1) 成员资格测试The total then is O(n) + O(n) => O(n), that is, the performance is linear with number of total elements of List1
+ List2
.那么总数是 O(n) + O(n) => O(n),也就是说,性能与List1
+ List2
的总元素数呈线性关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.