How to count the frequency of the elements in an unordered list?

后端 未结 30 3269
时光说笑
时光说笑 2020-11-22 02:37

I need to find the frequency of elements in an unordered list

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

output->

b =         


        
30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 02:53

    In Python 2.7 (or newer), you can use collections.Counter:

    import collections
    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    counter=collections.Counter(a)
    print(counter)
    # Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
    print(counter.values())
    # [4, 4, 2, 1, 2]
    print(counter.keys())
    # [1, 2, 3, 4, 5]
    print(counter.most_common(3))
    # [(1, 4), (2, 4), (3, 2)]
    

    If you are using Python 2.6 or older, you can download it here.

提交回复
热议问题