需要从保留订单的嵌套列表中删除重复项 [英] Need to remove duplicates from a nested list preserving the order

查看:76
本文介绍了需要从保留订单的嵌套列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似下面的列表

I have a list like below

L = [[1,2],[1,3],[1,4],[2,1],[2,5],[3,1],[3,2]]

输出应为

[[1,2],[1,3],[1,4],[2,5],[3,2]]

请注意,必须保留对和元素的顺序.换句话说,我无法对列表进行排序,因为元素对的顺序也需要保留.例如,我需要保留最后一个元素[3,2].如果我对它们进行排序并删除重复项,则将其更改为我不想要的[2,3]. 另外,当我说我需要删除重复项[1,2]或[2,1]被视为重复项时,我想从中保留[1,2].

Please note that the order for the pairs and the elements has to be preserved. In other words, I cannot sort the list because the elements order needs to be preserved for the pairs as well. For example, I need the last element [3,2] to be preserved. If i sort them and remove duplicates this will be changed to [2,3] which I do not want. Also when I say I need to remove duplicates [1,2] or [2,1] is considered to be a duplicate and I want to preserve [1,2] from this.

推荐答案

这类似于

This works similar to removing duplicates from a regular list whilst preserving order, but we need to do something about the sublists not being hashable and the order of the sublists being irrelevant.

我们可以使用冻结集同时解决这两个问题.

We can use frozen sets to solve both these issues at once.

>>> lst = [[1,2],[1,3],[1,4],[2,1],[2,5],[3,1],[3,2]] 
>>> seen = set()
>>> result = []
>>> 
>>> for x in lst:
...     s = frozenset(x)
...     if s not in seen:
...         result.append(x)
...         seen.add(s)
... 
>>> result
[[1, 2], [1, 3], [1, 4], [2, 5], [3, 2]]

这篇关于需要从保留订单的嵌套列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆