删除集合列表的重复项

2024-01-06

我有一个集合列表:

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

(实际上在我的例子中是倒数元组列表的转换)

我想删除重复项以获得:

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'

Or

>>> list(np.unique(L))
TypeError: cannot compare sets using cmp()

如何获取具有不同集合的集合列表?


最好的方法是将你的集合转换为frozensets (可散列),然后使用set只获得独特的集合,就像这样

>>> 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像这样

>>> [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 https://docs.python.org/3/library/collections.html#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}]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

删除集合列表的重复项 的相关文章

随机推荐