How to get unique values with respective occurrence count from a list in Python?

前端 未结 11 2076
孤独总比滥情好
孤独总比滥情好 2020-12-13 13:13

I have a list which has repeating items and I want a list of the unique items with their frequency.

For example, I have [\'a\', \'a\', \'b\', \'b\', \'b\']

11条回答
  •  难免孤独
    2020-12-13 14:05

    I know this isn't a one-liner... but to me I like it because it's clear to me that we pass over the initial list of values once (instead of calling count on it):

    >>> from collections import defaultdict
    >>> l = ['a', 'a', 'b', 'b', 'b']
    >>> d = defaultdict(int)
    >>> for i in l:
    ...  d[i] += 1
    ... 
    >>> d
    defaultdict(, {'a': 2, 'b': 3})
    >>> list(d.iteritems())
    [('a', 2), ('b', 3)]
    >>>
    

提交回复
热议问题