【问题标题】:Most Efficient way to calculate Frequency of values in a Python list?计算Python列表中值频率的最有效方法?
【发布时间】:2011-03-11 11:21:30
【问题描述】:

我正在寻找一种快速有效的方法来计算python中list项目的频率:

list = ['a','b','a','b', ......]

我想要一个频率计数器,它会给我这样的输出:

 [ ('a', 10),('b', 8) ...]

项目应按频率降序排列,如上所示。

【问题讨论】:

    标签: python list frequency


    【解决方案1】:

    Python2.7+

    >>> from collections import Counter
    >>> L=['a','b','a','b']
    >>> print(Counter(L))
    Counter({'a': 2, 'b': 2})
    >>> print(Counter(L).items())
    dict_items([('a', 2), ('b', 2)])
    

    python2.5/2.6

    >>> from collections import defaultdict
    >>> L=['a','b','a','b']
    >>> d=defaultdict(int)
    >>> for item in L:
    >>>     d[item]+=1
    >>>     
    >>> print d
    defaultdict(<type 'int'>, {'a': 2, 'b': 2})
    >>> print d.items()
    [('a', 2), ('b', 2)]
    

    【讨论】:

    • Python 2.5 的任何解决方案?我将它与 Google App Engine 一起使用
    • 当然,你可以使用 defaultdict。我将添加到我的答案中
    • 感谢您的快速回复。欣赏它。
    • Counter 不是最有效的方法;查看性能比较stackoverflow.com/questions/2522152/…
    • this 也可能很有趣,它说计数是 O(1) ...
    猜你喜欢
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2021-06-08
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    相关资源
    最近更新 更多