简体   繁体   中英

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

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}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM