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

4

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

我想比较这两个列表,但只考虑元组的第1个和第2个元素,并且基本上只是删除重复项,但不应考虑第二个列表中每个元组的第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_x中出现的元素,结果列表应该像这样:
[(1,3,65),(2,4,11), ...]

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

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

还可以通过元组的第二个元素对结果列表进行排序:

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

但现在的问题是:如果列表看起来像上面那样,如何实现这一点?
3个回答

3
您可以将list_x转换为一个集合,然后循环遍历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]

Demo -

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

0
尝试以下代码:
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])

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接