Divide a list into multiple lists based on a bin size

前端 未结 6 539
悲哀的现实
悲哀的现实 2021-01-18 03:02

I have a list containing more than 100,000 values in it.

I need to divide the list into multiple smaller lists based on a specific bin width say 0.1. Can anyone hel

6条回答
  •  不知归路
    2021-01-18 03:33

    Binning can be done with itertools.groupby:

    import itertools as it
    
    
    iterable = ['-0.234', '-0.04325', '-0.43134', '-0.315', '-0.6322', '-0.245',
                '-0.5325', '-0.6341', '-0.5214', '-0.531', '-0.124', '-0.0252']
    
    a,b,c,d,e,f,g = [list(g) for k, g in it.groupby(sorted(iterable), key=lambda x: x[:4])]
    c
    # ['-0.234', '-0.245']
    

    Note: this simple key function assumes the values in the iterable are between -0.0 and -10.0. Consider lambda x: "{:.1f}".format(float(x)) for general cases.

    See also this post for details on how groupby works.

提交回复
热议问题