python histogram one-liner

前端 未结 9 1024
一生所求
一生所求 2020-12-02 09:10

There are many ways to write a Python program that computes a histogram.

By histogram, I mean a function that counts the occurrence of objects in an iterable

9条回答
  •  一整个雨季
    2020-12-02 09:27

    One that works back to 2.3 (slightly shorter than Timmerman's, I think more readable) :

    L = 'abracadabra'
    hist = {}
    for x in L: hist[x] = hist.pop(x,0) + 1
    print hist
    {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}
    

提交回复
热议问题