简体   繁体   English

计算元组列表中唯一元素的数量,而不管Python中的顺序如何

[英]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.Counterfrozenset

>>> 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. 使用Frozenset规范化不同的元组。 And then checking the amount of items in the resulting set: 然后检查结果集中的项目数量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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