python - 如何以最快的方式从 Python 中的计数器中删除频率最低的元素?

标签 python data-structures

我想实现一个计数器,当计数器的大小超过某个阈值时,它会丢弃频率最低的元素。为此,我需要删除出现频率最低的元素。

在 Python 中最快的方法是什么?

我知道 counter.most_common()[-1],但它会创建一个完整的列表,并且在大量完成时看起来很慢?是否有更好的命令(或者可能是不同的数据结构)?

最佳答案

您可以通过借用 most_common 的实现并进行必要的更改来实现 least_common

引用collections source in Py2.7 :

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.iteritems(), key=_itemgetter(1), reverse=True)
    return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))

要更改它以检索最不常见的,我们只需要进行一些调整。

import collections
from operator import itemgetter as _itemgetter
import heapq as _heapq


class MyCounter(collections.Counter):
    def least_common(self, n=None):
        if n is None:
            return sorted(self.iteritems(), key=_itemgetter(1), reverse=False)  # was: reverse=True
        return _heapq.nsmallest(n, self.iteritems(), key=_itemgetter(1))  # was _heapq.nlargest

测试:

c = MyCounter("abbcccddddeeeee")
assert c.most_common() == c.least_common()[::-1]
assert c.most_common()[-1:] == c.least_common(1)

关于python - 如何以最快的方式从 Python 中的计数器中删除频率最低的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37620222/

相关文章:

python - Numpy 向量/矩阵乘法意外工作

python - Django:解压参数列表以在聚合查询中使用

java - 矩阵中的最小分割数

c++ - 我可以知道为什么这个函数的参数不是 int 类型吗?我不明白这里指针的整个概念

python - 使用 subprocess.Popen 启动子进程并在其运行时读取其输出

python - 将 TXT 加载到 postgres 数据库中,将不存在的列填充为 null

c++ - 如何实现缓存友好的动态二叉树?

algorithm - 将黑盒数组排序算法更改为稳定算法

algorithm - 压缩稀疏行 (CSR) : How do you store empty rows?

python - 安装 ODBC 驱动程序 heroku