Best way to turn word list into frequency dict

后端 未结 8 613
无人及你
无人及你 2020-12-03 17:07

What\'s the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?<

8条回答
  •  被撕碎了的回忆
    2020-12-03 17:35

    I have to share an interesting but kind of ridiculous way of doing it that I just came up with:

    >>> class myfreq(dict):
    ...     def __init__(self, arr):
    ...         for k in arr:
    ...             self[k] = 1
    ...     def __setitem__(self, k, v):
    ...         dict.__setitem__(self, k, self.get(k, 0) + v)
    ... 
    >>> myfreq(['a', 'b', 'b', 'a', 'b', 'c'])
    {'a': 2, 'c': 1, 'b': 3}
    

提交回复
热议问题