简体   繁体   English

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

[英]Python: Compare 2 lists of tuples of different size

I have 2 lists of tuples. 我有2个元组列表。 The first list contains x entries with 2-tuples while the other list contains y (more) entries with 3-tuples. 第一个列表包含带有2元组的x个条目,而另一个列表包含带有3个元组的y(更多)条目。

I want to compare both lists, but only the 1st and 2nd element of the tuples and basically just remove dublicates, but the 3rd entry of every tuple in the 2nd list should be not considered during the comparison. 我想比较两个列表,但只比较元组的第一个和第二个元素,基本上只是删除dublicates,但在比较期间不应考虑第二个列表中每个元组的第三个条目。

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

Now I want to create a new list where all elements from list_y which also occur in list_x are removed. 现在我想创建一个新列表,其中list_y中也出现在list_x中的所有元素都将被删除。 The resulting list should look like this: 结果列表应如下所示:

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

For lists of tuples with the same size it works simply by just converting the lists to a set and subtract both lists: 对于具有相同大小的元组列表,只需将列表转换为集合并减去两个列表即可:

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

it is also possible to sort the resulting list by the 2nd element of the tuples: 也可以通过元组的第二个元素对结果列表进行排序:

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

But now the question is: how is it possible to do this if the lists look like above? 但现在问题是:如果列表如上所示,怎么可能这样做呢?

You can convert list_x to a set, and then loop over list_y and check if the first two elements of list_y are present in the set or not, if not present include them in the resultant list, and this can be done in a list comprehension as given below. 你可以将list_x转换为一个集合,然后遍历list_y并检查list_y的前两个元素是否存在于集合中,如果不存在则将它们包含在结果列表中,这可以在列表list_y中完成如下。 Example - 示例 -

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

Try the following code: 请尝试以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM