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

前端 未结 11 2072
孤独总比滥情好
孤独总比滥情好 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 13:51

    If your items are grouped (i.e. similar items come together in a bunch), the most efficient method to use is itertools.groupby:

    >>> [(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])]
    [('a', 2), ('b', 3)]
    

提交回复
热议问题