【问题标题】:Delete all tuples from a list, if the first two elements of another tuple matches如果另一个元组的前两个元素匹配,则从列表中删除所有元组
【发布时间】:2023-01-26 01:09:14
【问题描述】:

我有两个元组列表,如果 list2 中元组的前两个元素与 list1 中元组的前两个元素匹配,我想从 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')]

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

【问题讨论】:

标签: python list tuples element


【解决方案1】:

您可以将列表理解与 all 结合使用,以仅获取与第二个列表中的任何元素都不匹配的元素。

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

【讨论】:

  • 谢谢 !!!我试了几个小时,这正是我所需要的。
  • @Peterslav 乐于提供帮助。
【解决方案2】:

list2中每个元组的前两个元素,使用set()去重条目,然后过滤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')]

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')]

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多