Count the number of unique elements of a list of t

2019-01-27 00:06发布

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

标签: python list set
2条回答
▲ chillily
2楼-- · 2019-01-27 00:32

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}
查看更多
我命由我不由天
3楼-- · 2019-01-27 00:39

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
查看更多
登录 后发表回答