[英]Delete all tuples from a list, if the first two elements of another tuple matches
我有兩個元組列表,如果 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')]
您可以將列表推導式與all
一起使用,以僅獲取與第二個列表中的任何元素都不匹配的元素。
res = [x for x in list1 if all(x[:2] != y[:2] for y in list2)]
取出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')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.