【问题标题】:Count the number of unique elements of a list of tuples regardless of order in Python计算元组列表中唯一元素的数量,无论 Python 中的顺序如何
【发布时间】:2013-11-30 11:55:53
【问题描述】:

我有一个包含以下形式的元组的列表:

[('s1', 's2'),('s3','s32')...('s2','s1')]`

考虑到顺序并不重要,我如何计算不同元组的数量?

示例:('s1','s2')('s2','s1') 相同

【问题讨论】:

    标签: python list set


    【解决方案1】:

    使用frozenset 标准化您的不同元组。然后检查结果集中的项目数量:

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

    【讨论】:

      【解决方案2】:

      使用collections.Counterfrozenset

      >>> from collections import Counter
      >>> Counter(map(frozenset, [('s1', 's2'),('s3','s32'), ('s2','s1')]))
      Counter({frozenset(['s2', 's1']): 2, frozenset(['s3', 's32']): 1})
      

      将键作为元组获取:

      >>> 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}
      

      【讨论】:

        猜你喜欢
        • 2016-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-17
        • 2021-10-13
        • 1970-01-01
        • 2022-11-25
        相关资源
        最近更新 更多