如何从python中的列表中删除重复的元组? [英] How to remove duplicate tuples from a list in python?
问题描述
我有一个包含元组列表的列表,如下所示.
I have a list that contains list of tuples as follows.
mylist = [['xxx', 879], ['yyy', 315], ['xxx', 879], ['zzz', 171], ['yyy', 315]]
我想从mylist
中删除重复的元组,并获得如下输出.
I want to remove the duplicate tuples from mylist
and get an output as follows.
mylist = [['xxx', 879], ['yyy', 315], ['zzz', 171]]
似乎python中的set
不适用于它.
It seems like set
in python does not work for it.
mylist = list(set(mylist))
在python中有任何快速简便的方法(也许使用库)吗?
Is there any fast and easy way of doing this in python (perhaps using libraries)?
推荐答案
您需要编写保留第一个子列表的代码,其余部分删除.最简单的方法是反转mylist
,将其加载到dict
对象,然后再次将其键值对作为列表检索.
You need to write code that keeps the first of the sub-lists, dropping the rest. The simplest way to do this is to reverse mylist
, load it into an dict
object, and retrieve its key-value pairs as lists again.
>>> list(map(list, dict(mylist).items()))
或者,使用列表理解-
>>> [list(v) for v in dict(mylist).items()]
[['zzz', 171], ['yyy', 315], ['xxx', 879]]
请注意,此答案不维护顺序!另外,如果您的子列表可以包含2个以上的元素,则该方法涉及对数据的郁金香版本进行哈希处理,例如 @JohnJosephFernandez的答案显示,这将是最好的选择.
Note, that this answer does not maintain order! Also, if your sub-lists can have more than 2 elements, an approach involving hashing the tuplized versions of your data, as @JohnJosephFernandez' answer shows, would be the best thing to do.
这篇关于如何从python中的列表中删除重复的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!