简体   繁体   English

如何从列表列表中删除列表集

[英]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]
  1. Convert the list of items to exclude to a set of tuples将要排除的项目列表转换为一set tuples

    • This conversion is O(n)这个转换是 O(n)
    • 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可散列的
  2. Check membership for each element of List1检查List1的每个元素的成员资格

    • This check is also O(n)这个检查也是 O(n)
    • The 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM