python histogram one-liner

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

    It's kinda cheaty to import modules for oneliners, so here's a oneliner that is O(n) and works at least as far back as Python2.4

    >>> f=lambda s,d={}:([d.__setitem__(i,d.get(i,0)+1) for i in s],d)[-1]
    >>> f("ABRACADABRA")
    {'A': 5, 'R': 2, 'B': 2, 'C': 1, 'D': 1}
    

    And if you think __ methods are hacky, you can always do this

    >>> f=lambda s,d=lambda:0:vars(([setattr(d,i,getattr(d,i,0)+1) for i in s],d)[-1])
    >>> f("ABRACADABRA")
    {'A': 5, 'R': 2, 'B': 2, 'C': 1, 'D': 1}
    

    :)

提交回复
热议问题