Python:比较2个不同大小的元组列表

Python: Compare 2 lists of tuples of different size

我有 2 个元组列表。第一个列表包含 x 个具有 2 元组的条目,而另一个列表包含 y 个(更多)具有 3 元组的条目。

我想比较两个列表,但只比较元组的第一个和第二个元素,基本上只是删除重复项,但是在比较过程中不应考虑第二个列表中每个元组的第三个条目。

list_x=[(1,1),(1,2),(2,3),(2,5),(4,6), ...]
list_y=[(1,1,33),(1,3,65),(2,4,11), ...]

现在我想创建一个新列表,其中 list_y 中也出现在 list_x 中的所有元素都被删除。 结果列表应如下所示:

[(1,3,65),(2,4,11), ...]

对于大小相同的元组列表,只需将列表转换为集合并减去两个列表即可:

newlist = list(set(list_y) - set(list_x))

也可以按元组的第二个元素对结果列表进行排序:

newlist.sort(key=lambda tup: tup[1])

但现在的问题是:如果列表像上面那样,怎么可能做到这一点?

试试下面的代码:

set_x = set(list_x)
answer = sorted([t for t in list_y if (t[0], t[1]) not in set_x], key=lambda t:t[1])

可以把list_x转成集合,然后循环遍历list_y,检查集合中是否存在list_y的前两个元素,如果不存在将它们包含在结果列表中,这可以在下面给出的列表理解中完成。示例 -

list_x=[(1,1),(1,2),(2,3),(2,5),(4,6), ...]
list_y=[(1,1,33),(1,3,65),(2,4,11), ...]

list_x_set = set(list_x)

result = [item for item in list_y if item[0:2] not in list_x_set]

演示 -

In [57]: list_x=[(1,1),(1,2),(2,3),(2,5),(4,6)]

In [58]: list_y=[(1,1,33),(1,3,65),(2,4,11)]

In [59]: list_x_set = set(list_x)

In [60]: result = [item for item in list_y if item[0:2] not in list_x_set]

In [62]: result
Out[62]: [(1, 3, 65), (2, 4, 11)]
with for loops 

list_x=[(1,1),(1,2),(2,3),(2,5),(4,6)]
list_y=[(1,1,33),(1,3,65),(2,4,11)]

for elx in list_x:
    for ely in list_y:
        if ely[:-1] == elx:
            list_y.remove(ely)


print(list_y)

[(1, 3, 65), (2, 4, 11)]