vlad
vlad

Reputation: 811

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(lst)
TypeError: unhashable type: 'set'

Upvotes: 0

Views: 1137

Answers (6)

Robᵩ
Robᵩ

Reputation: 168626

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}

Upvotes: 2

Jo-el
Jo-el

Reputation: 440

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

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

Upvotes: 0

Alexander
Alexander

Reputation: 109546

>>> reduce(lambda a, b: a.union(b), lst)
{0, 1, 2}

EDIT

Given that the OP appears to want unique subsets:

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

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

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.

Upvotes: 0

Craig Burgler
Craig Burgler

Reputation: 1779

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

Upvotes: 0

spruceb
spruceb

Reputation: 621

If by "unique items" you mean unique sets, you could just use frozenset, which is a hashable but immutable version of set. You could either build your sets as frozenset objects initially, or if you need to mutate them, do something like:

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

Then:

>>> uniques
set([frozenset([1, 2]), frozenset([0, 1])])

Upvotes: 2

Related Questions