【问题标题】:collections.Counter: most_common INCLUDING equal countscollections.Counter: most_common 包括相等的计数
【发布时间】:2015-01-05 23:55:46
【问题描述】:

collections.Counter 中,方法most_common(n) 仅返回列表中的n 个最频繁的项目。我确实需要,但我也需要包括相同的计数。

from collections import Counter
test = Counter(["A","A","A","B","B","C","C","D","D","E","F","G","H"])
-->Counter({'A': 3, 'C': 2, 'B': 2, 'D': 2, 'E': 1, 'G': 1, 'F': 1, 'H': 1})
test.most_common(2)
-->[('A', 3), ('C', 2)

我需要[('A', 3), ('B', 2), ('C', 2), ('D', 2)] 因为在这种情况下,它们的计数与 n=2 相同。我的真实数据是关于 DNA 代码的,可能非常大。我需要它有点效率。

【问题讨论】:

    标签: python collections python-collections


    【解决方案1】:

    对于较小的集合,只需编写一个简单的生成器:

    >>> test = Counter(["A","A","A","B","B","C","C","D","D","E","F","G","H"])
    >>> g=(e for e in test.most_common() if e[1]>=2)
    >>> list(g)
    [('A', 3), ('D', 2), ('C', 2), ('B', 2)]
    

    对于更大的集合,请使用ifilter(或仅在 Python 3 上使用 filter):

    >>> list(ifilter(lambda t: t[1]>=2, test.most_common()))
    [('A', 3), ('C', 2), ('B', 2), ('D', 2)]
    

    或者,由于 most_common 已经排序,只需使用 for 循环并在生成器中的所需条件处中断:

    def fc(d, f):
        for t in d.most_common():
            if not f(t[1]): 
                break
            yield t
    
    >>> list(fc(test, lambda e: e>=2)) 
    [('A', 3), ('B', 2), ('C', 2), ('D', 2)]
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      from itertools import takewhile
      
      def get_items_upto_count(dct, n):
        data = dct.most_common()
        val = data[n-1][1] #get the value of n-1th item
        #Now collect all items whose value is greater than or equal to `val`.
        return list(takewhile(lambda x: x[1] >= val, data))
      
      test = Counter(["A","A","A","B","B","C","C","D","D","E","F","G","H"])
      
      print get_items_upto_count(test, 2)
      #[('A', 3), ('C', 2), ('B', 2), ('D', 2)]
      

      【讨论】:

      • 你有错别字,请更正,应该是get_item_upto_count(test, 2)
      • 为什么不直接取n个元素的切片,而next的取值等于n切片的最后一个元素?
      • @PadraicCunningham 吃什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 2013-09-06
      • 2018-01-23
      • 2012-06-21
      相关资源
      最近更新 更多