Home > Enterprise >  Unique value from the list of sets
Unique value from the list of sets

Time:08-14

I have a list e.g

['abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba']

and

list(map(set, x))

out:

[{'a', 'b', 'c'},
 {'a', 'b', 'c'},
 {'a', 'b', 'c'},
 {'f', 'o'},
 {'a', 'b', 'c'},
 {'a', 'b', 'c'},
 {'a', 'b', 'c'}]

I would like to receive a set from the set I mean. Expected output:

[ {'a', 'b', 'c'},
 {'f', 'o'}]

My second question. How to get a dictionary of counts?

{{'a', 'b', 'c'} : 6,
 {'f', 'o'} : 1}}

CodePudding user response:

For your first question, How can I create a Set of Sets in Python? might be what you are looking for. As for your second question, the simplest way is to use Counter. This link may be useful for you.

Code:

from collections import Counter
x = ['abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba']
a = list(map(frozenset, x))
print(set(a))
print(Counter(a))

Output:

{frozenset({'a', 'c', 'b'}), frozenset({'o', 'f'})}

Counter({frozenset({'a', 'c', 'b'}): 6, frozenset({'o', 'f'}): 1})

  • Related