删除集合列表的重复 [英] removing duplicates of a list of sets
本文介绍了删除集合列表的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组集合:
L = [set([1, 4]), set([1, 4]), set([1, 2]), set([1, 2]), set([2, 4]), set([2, 4]), set([5, 6]), set([5, 6]), set([3, 6]), set([3, 6]), set([3, 5]), set([3, 5])]
(实际上在我的情况下转换一个互惠元组列表)
(actually in my case a conversion of a list of reciprocal tuples)
,我想删除重复项以获取:
and I want to remove duplicates to get :
L = [set([1, 4]), set([1, 2]), set([2, 4]), set([5, 6]), set([3, 6]), set([3, 5])]
但是如果我尝试:
>>> list(set(L))
TypeError: unhashable type: 'set'
或
>>> list(np.unique(L))
TypeError: cannot compare sets using cmp()
如何获取不同集合的集合列表?
How do I get a list of sets with distinct sets?
推荐答案
最好的方法是将您的集合转换为 frozenset
s(可以是hashable),然后使用 set
来获取唯一的集合,像这样
The best way is to convert your sets to frozenset
s (which are hashable) and then use set
to get only the unique sets, like this
>>> list(set(frozenset(item) for item in L))
[frozenset({2, 4}),
frozenset({3, 6}),
frozenset({1, 2}),
frozenset({5, 6}),
frozenset({1, 4}),
frozenset({3, 5})]
如果你想要它们作为集合,那么你可以将它们转换回 set
像这样
If you want them as sets, then you can convert them back to set
s like this
>>> [set(item) for item in set(frozenset(item) for item in L)]
[{2, 4}, {3, 6}, {1, 2}, {5, 6}, {1, 4}, {3, 5}]
如果您还希望维护订单,同时删除重复项,则可以使用 collections.OrderedDict
,像这样
>>> from collections import OrderedDict
>>> [set(i) for i in OrderedDict.fromkeys(frozenset(item) for item in L)]
[{1, 4}, {1, 2}, {2, 4}, {5, 6}, {3, 6}, {3, 5}]
这篇关于删除集合列表的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文