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

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

    With Python 2.7+, you can use collections.Counter.

    Otherwise, see this counter receipe.

    Under Python 2.7+:

    from collections import Counter
    input =  ['a', 'a', 'b', 'b', 'b']
    c = Counter( input )
    
    print( c.items() )
    

    Output is:

    [('a', 2), ('b', 3)]

提交回复
热议问题