[英]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')
示例:(
('s1','s2')
与('s2','s1')
Using collections.Counter
and frozenset
: 使用
collections.Counter
和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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.