简体   繁体   English

集列表中的唯一项

[英]Unique items in list of sets

If I have list of sets: 如果我有套装清单:

>>> lst = [{1, 2}, {0, 1}, {1, 2}]

How to return unique items? 如何退还独特物品?

Trying well known set() does not work: 尝试众所周知的set()不起作用:

>>> set(lst)
TypeError: unhashable type: 'set'

If by "unique items" you mean unique sets, you could just use frozenset , which is a hashable but immutable version of set . 如果“特殊物品”你的意思是唯一集,你可以只使用frozenset ,这是一个哈希的,但不变的版本set You could either build your sets as frozenset objects initially, or if you need to mutate them, do something like: 您可以将集合最初构建为frozenset对象,或者如果需要对其进行突变,请执行以下操作:

uniques = set(frozenset(s) for s in lst)

Then: 然后:

>>> uniques
set([frozenset([1, 2]), frozenset([0, 1])])
In [8]: lst = [{1, 2}, {0, 1}, {1, 2}]

In [9]: reduce(set.union, lst)
Out[9]: {0, 1, 2}

Edit: 编辑:

A better version of above: 上面的更好的版本:

In [1]: lst = [{1, 2}, {0, 1}, {1, 2}]

In [2]: set.union(*lst)
Out[2]: {0, 1, 2}
>>> reduce(lambda a, b: a.union(b), lst)
{0, 1, 2}

EDIT 编辑

Given that the OP appears to want unique subsets: 鉴于OP似乎需要唯一的子集:

>>> set(tuple(sorted(s)) for s in lst)
{(0, 1), (1, 2)}

You may achieve this by: 您可以通过以下方法实现此目的:

>>> lst = [{1, 2}, {0, 1}, {1, 2}]
>>> set(frozenset(s) for s in lst)   
set([frozenset([1, 2]), frozenset([0, 1])])

Check Frozen Set document for more information. 检查冻结集文档以获取更多信息。

def get_unique_sets(l):
    unique_sets = []
    for s in l:
        if s not in unique_sets:
            unique_sets.append(s)
    return unique_sets

lst = [{1, 2}, {0, 1}, {1, 2}]
print(get_unique_sets(lst))

Output 输出量

[{1, 2}, {0, 1}]

Do your input list items have to be sets or could they be tuples instead? 输入列表项是否必须设置或可以是元组?

set() works on tuples in my test (py 2.7): set()在我的测试中适用于元组(py 2.7):

>>> lst = [(1,2), (0,1), (1,2)]
>>> set(lst)
set([(1, 2), (0, 1)])

If your input is always a list of sets, you can just do a transformation to tuples before and a transformation back to sets after: 如果您的输入始终是集合的列表,则只需将其转换为之前的元组,然后将其转换为之后的集:

>>> lst = [{1, 2}, {0, 1}, {1, 2}]
>>> lst
[set([1, 2]), set([0, 1]), set([1, 2])]
>>> set(lst)
TypeError: unhashable type: 'set'
>>> lst2 = [tuple(x) for x in lst]
>>> lst2
[(1, 2), (0, 1), (1, 2)]
>>> lst2 = set(lst2)
>>> lst2
set([(1, 2), (0, 1)])
>>> lst2 = list(lst2)
>>> lst2
[(1, 2), (0, 1)]
>>> lst = [set(x) for x in lst2]
>>> lst
[set([1, 2]), set([0, 1])]

Not sure if this is the best option, but it works in the example case you gave, hope this helps :) 不知道这是否是最好的选择,但是它可以在您给出的示例中起作用,希望这会有所帮助:)

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

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