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

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

    If you are willing to use a 3rd party library, NumPy offers a convenient solution. This is particularly efficient if your list contains only numeric data.

    import numpy as np
    
    L = ['a', 'a', 'b', 'b', 'b']
    
    res = list(zip(*np.unique(L, return_counts=True)))
    
    # [('a', 2), ('b', 3)]
    

    To understand the syntax, note np.unique here returns a tuple of unique values and counts:

    uniq, counts = np.unique(L, return_counts=True)
    
    print(uniq)    # ['a' 'b']
    print(counts)  # [2 3]
    

    See also: What are the advantages of NumPy over regular Python lists?

提交回复
热议问题