Joylove
Joylove

Reputation: 414

python list of sets find symmetric difference in all elements

Consider this list of sets

my_input_list= [
{1,2,3,4,5},
{2,3,7,4,5},
set(),
{1,2,3,4,5,6},
set(),]

I want to get the only exclusive elements 6 and 7 as the response, list or set. Set preferred.

I tried print reduce(set.symmetric_difference,my_input_list) but that gives

{2,3,4,5,6,7}

And i tried sorting the list by length, smallest first raises an error due to two empty sets. Largest first gives the same result as unsorted.

Any help or ideas please? Thanks :)

Upvotes: 2

Views: 368

Answers (2)

MegaIng
MegaIng

Reputation: 7886

You could use itertools.chain and collection.Counter:

from itertools import chain
from collections import Counter

r = {k for k,v in Counter(chain.from_iterable(my_input_list)).items() if v==1}

Upvotes: 2

cs95
cs95

Reputation: 403128

Looks like the most straightforward solution is to count everything and return the elements that only appear once.

This solution uses chain.from_iterable (to flatten your sets) + Counter (to count things). Finally, use a set comprehension to filter elements with count == 1.

from itertools import chain
from collections import Counter

c = Counter(chain.from_iterable(my_input_list))
print({k for k in c if c[k] == 1})
{6, 7}

A quick note; the empty literal {} is used to indicate an empty dict, not set. For the latter, use set().

Upvotes: 5

Related Questions