提问人:Codingamethyst 提问时间:9/3/2022 最后编辑:Codingamethyst 更新时间:9/3/2022 访问量:75
如何从列表列表中删除列表集
How to remove set of lists from a list of lists
问:
我有 2 个字符串列表
List1 = [["Hey there"], ["hi"], ["hello"]]
List2 = [["hi"], ["hello"]]
有没有一种 O(n) 方法可以删除 from 的元素?List2
List1
期望输出 =[["Hey there"]]
答:
1赞
Pi Marillion
9/3/2022
#1
您可以通过两个 O(n) 步骤来执行此操作:
List2_set = set(map(tuple, List2))
List1_filtered = [row for row in List1 if tuple(row) not in List2_set]
将要排除的项目列表转换为
set
tuples
- 此转换为 O(n)
set
是必需的,因为检查集合的隶属关系是 O(1) 而不是 O(n)tuple
是项所必需的,而不是 ,因为 是可散列的set
list
tuple
检查每个元素的成员资格
List1
- 此检查也是 O(n)
- 该集合使用哈希表来允许 O(1) 成员资格测试
set
然后,总数为 O(n) + O(n) => O(n),也就是说,性能与 + 的总元素数呈线性关系。List1
List2
评论
List1 == List2