papafe
papafe

Reputation: 3070

Count the number of unique elements of a list of tuples regardless of order in Python

I have a list that contains tuples in the form:

[('s1', 's2'),('s3','s32')...('s2','s1')]`

How can I count the number of distinct tuples, considering that the order is not important?

Example: ('s1','s2') is the same as ('s2','s1')

Upvotes: 2

Views: 1363

Answers (2)

Inbar Rose
Inbar Rose

Reputation: 43437

Using frozenset to normalize your distinct tuples. And then checking the amount of items in the resulting set:

>>> l = [('s1', 's2'), ('s3','s32'), ('s2','s1')]
>>> len(set(map(frozenset, l)))
2

Upvotes: 6

falsetru
falsetru

Reputation: 368904

Using collections.Counter and frozenset:

>>> from collections import Counter
>>> Counter(map(frozenset, [('s1', 's2'),('s3','s32'), ('s2','s1')]))
Counter({frozenset(['s2', 's1']): 2, frozenset(['s3', 's32']): 1})

To get keys as tuples:

>>> c = Counter(map(frozenset, [('s1', 's2'),('s3','s32'), ('s2','s1')]))
>>> {tuple(s): count for s, count in c.most_common()}
{('s2', 's1'): 2, ('s3', 's32'): 1}

Upvotes: 6

Related Questions