python histogram one-liner

前端 未结 9 1066
一生所求
一生所求 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:31

    Python 3.x does have reduce, you just have to do a from functools import reduce. It also has "dict comprehensions", which have exactly the syntax in your example.

    Python 2.7 and 3.x also have a Counter class which does exactly what you want:

    from collections import Counter
    cnt = Counter("abracadabra")
    

    In Python 2.6 or earlier, I'd personally use a defaultdict and do it in 2 lines:

    d = defaultdict(int)
    for x in xs: d[x] += 1
    

    That's clean, efficient, Pythonic, and much easier for most people to understand than anything involving reduce.

提交回复
热议问题