sort list of floating-point numbers in groups

前端 未结 2 1830
借酒劲吻你
借酒劲吻你 2021-02-15 11:12

I have an array of floating-point numbers, which is unordered. I know that the values always fall around a few points, which are not known. For illustration, this list



        
2条回答
  •  广开言路
    2021-02-15 11:37

    You can try the following method:

    Sort the array first, and use diff() to calculate the difference between two continuous values. the difference larger than threshold can be consider as the split position:

    import numpy as np
    x = [10.01,5.001,4.89,5.1,9.9,10.1,5.05,4.99]
    x = np.sort(x)
    th = 0.5
    print [group.mean() for group in np.split(x, np.where(np.diff(x) > th)[0]+1)]
    

    the result is:

    [5.0061999999999998, 10.003333333333332]
    

提交回复
热议问题