从 python 中的另一个元组列表中减去元组列表

问题描述 投票:0回答:0

我有两个元组列表,但想象一下很长的元组列表,我的想法是获得这两个条件

  1. 仅在 list2 中的元组
  2. 摆脱单独的元组,其中 list1 中元组的第一个元素与 list2 中元组的第一个元素匹配
list1 = [(1,2), (1,3), (1,5), (3,4), (2,6)]
list2 = [(1,2), (1,3)]

预期产出

result = [(3, 4), (2,6)]

合并结果+list1后

final_rest = [(1,2), (1,3),(3,4), (2,6)]

我试过这种方法,但结果是重复的

[x for x in list1 for y in list2 if x[1] != y[1]]

这也摆脱了

(1,5)
但它不起作用

[x for x in list1 if x in list2 and x[0] != list2[0]] 

这种重复的方法

l = []
for x in list1:
    for y in list2:
        if x not in list2 and x[0] != y[0]:
            l.append(x)

[(3, 5), (3, 5), (5, 8), (5, 8)] # I want without duplicates
python tuples list-comprehension
© www.soinside.com 2019 - 2024. All rights reserved.