uniquify an array/list with a tolerance in python (uniquetol equivalent)

前端 未结 2 1282
迷失自我
迷失自我 2020-12-20 17:03

I want to find the unique elements of an array in a certain range of tolerance

For instance, for an array/list

[1.1 , 1.3 , 1.9 , 2.0 , 2.5 , 2.9]
         


        
2条回答
  •  醉梦人生
    2020-12-20 17:18

    In pure Python 2, I wrote the following:

    a = [1.1, 1.3, 1.9, 2.0, 2.5, 2.9]                                              
    
    # Per http://fr.mathworks.com/help/matlab/ref/uniquetol.html                                                                                    
    tol = max(map(lambda x: abs(x), a)) * 0.3                                       
    
    a.sort()                                                                        
    
    results = [a.pop(0), ]                                                          
    
    for i in a:
        # Skip items within tolerance.                                                                     
        if abs(results[-1] - i) <= tol:                                             
            continue                                                                
        results.append(i)                                                           
    
    print a                                                                         
    print results
    

    Which results in

    [1.3, 1.9, 2.0, 2.5, 2.9]
    [1.1, 2.0, 2.9]
    

    Which is what the spec seems to agree with, but isn't consistent with your example.

    If I just set the tolerance to 0.3 instead of max(map(lambda x: abs(x), a)) * 0.3, I get:

    [1.3, 1.9, 2.0, 2.5, 2.9]
    [1.1, 1.9, 2.5, 2.9]
    

    ...which is consistent with your example.

提交回复
热议问题