简体   繁体   中英

How to remove set of lists from a list of lists

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]
  1. Convert the list of items to exclude to a set of tuples

    • This conversion is O(n)
    • 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
  2. Check membership for each element of List1

    • This check is also O(n)
    • The 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.

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