Home > Software design >  Delete all tuples from a list, if the first two elements of another tuple matches
Delete all tuples from a list, if the first two elements of another tuple matches

Time:01-26

i have two tuple lists, and i want to delete all tuples from list1, if the first two elements of a tuple from list2 matches with the first two elements of a tuple from list1.

list1 = [('google', 'data', '1'), ('google', 'data', '2'), ('google', 'data', '3'), ('google', 'data', '4'), ('google', 'WORLD', '1')]

list2 = [('google', 'data', '1'), ('google', 'HELLO', '2'), ('google', 'BLA', '3')]

Result: list1 = [('google', 'WORLD', '1')]

CodePudding user response:

You can use a list comprehension with all to get only elements that do not match with any of the elements from the second list.

res = [x for x in list1 if all(x[:2] != y[:2] for y in list2)]

CodePudding user response:

Take the first first two elements of each tuple in list2, use set() to deduplicate entries, then filter elements in list1 that are not in this set.

list1 = [('google', 'data', '1'), ('google', 'data', '2'), ('google', 'data', '3'),
         ('google', 'data', '4'), ('google', 'WORLD', '1')]
list2 = [('google', 'data', '1'), ('google', 'HELLO', '2'), ('google', 'BLA', '3')]

list2_pairs = set(map(lambda tpl: tpl[0:2], list2))
print(list2_pairs)  # {('google', 'BLA'), ('google', 'HELLO'), ('google', 'data')}
list1_result = list(filter(lambda tpl: tpl[0:2] not in list2_pairs, list1))
print(list1_result)  # [('google', 'WORLD', '1')]
  • Related