Most Efficient way to calculate Frequency of values in a Python list?

前端 未结 1 787
灰色年华
灰色年华 2021-01-01 16:57

I am looking for a fast and efficient way to calculate the frequency of list items in python:

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


        
相关标签:
1条回答
  • 2021-01-01 17:52

    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)]
    
    0 讨论(0)
提交回复
热议问题