【问题标题】:Filtered most_common() for Counter in Python在 Python 中为 Counter 过滤 most_common()
【发布时间】:2014-09-19 03:59:32
【问题描述】:

我有一个格式为 {(f1, f2): counts} 的计数器。当我对此运行 Counter.most_common() 时,我得到了正确的结果,但我想过滤 most_common() 以获取 f2 上的某些过滤器。例如 f2 = 'A' 应该返回 f2 = 'A' 的 most_common 元素。如何做到这一点?

【问题讨论】:

  • 在手机上,所以不能确定,但​​试试sorted([item for item in counter.items() if item[0][1]=='A'], key=operator.itemgetter(1), reverse=True)[:10]
  • @roippi 成功了。如果您填写答案,我会接受。

标签: python python-2.7 dictionary counter


【解决方案1】:

如果我们查看Counter 的源代码,我们会看到它使用heapq 保留O(n + k log n),其中k 是想要的密钥数量,nCounter 的大小,而不是O(n log n)

def most_common(self, n=None):
    '''List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.

    >>> Counter('abcdeabcdabcaba').most_common(3)
    [('a', 5), ('b', 4), ('c', 3)]

    '''
    # Emulate Bag.sortedByCount from Smalltalk
    if n is None:
        return sorted(self.items(), key=_itemgetter(1), reverse=True)
    return _heapq.nlargest(n, self.items(), key=_itemgetter(1))

因为这不仅仅是O(n),我们可以只过滤计数器并获取它的项目:

counts = Counter([(1, "A"), (2, "A"), (1, "A"), (2, "B"), (1, "B")])

Counter({(f1, f2): n for (f1, f2), n in counts.items() if f2 == "A"}).most_common(2)
#>>> [((1, 'A'), 2), ((2, 'A'), 1)]

虽然展开它可能会稍微快一点,但如果这很重要的话:

import heapq
from operator import itemgetter

filtered = [((f1, f2), n) for (f1, f2), n in counts.items() if f2 == "A"]
heapq.nlargest(2, filtered, key=itemgetter(1))
#>>> [((1, 'A'), 2), ((2, 'A'), 1)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多