Count the number of unique elements of a list of t

2019-01-27 00:16发布

问题:

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

回答1:

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}


回答2:

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


标签: python list set