python histogram one-liner

前端 未结 9 937
一生所求
一生所求 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}
    

    :)

    0 讨论(0)
  • 2020-12-02 09:34
    import pandas as pd
    
    pd.Series(list(L)).value_counts()
    
    0 讨论(0)
  • 2020-12-02 09:35
    $d{$_} += 1 for split //, 'abracadabra';
    
    0 讨论(0)
提交回复
热议问题