How to remove similar but not duplicate items from a list?

I have a list:

values = [[6.23234121,6.23246575],[1.352672,1.352689],[6.3245,123.35323,2.3]]

How can I go through this list and delete all elements within 0.01 , for other elements in the same list.

I know how to do this for a specific set of lists using del, but I want it to be common if it has n lists and each list has n elements.

What I want to do, do some operation on this list

values = [[6.23234121,6.23246575],[1.352672,1.352689],[6.3245,123.35323,2.3]]

and get this conclusion

new_values = [[6.23234121],[1.352672],[6.3245,123.35323,2.3]]
0
source share
1 answer

I am going to write a function for this for a single list, for example

>>> compact([6.23234121,6.23246575], tol=.01)
[6.23234121]

Then you can only make it work with your nested structure with [compact(l) for l in lst].

, ; @DSM [0, 0.005, 0.01, 0.015, 0.02] [0, 0.0.15] (, > >=, [0, 0.01, 0.02]). - , , .


-, , . O (n ^ 2):

def compact(lst, tol):
    new = []
    for el in lst:
        if all(abs(el - x) > tol for x in new):
            new.append(el)
    return compact

. , , . - :

import collections
import math

def compact(lst, tol):
    round_digits = -math.log10(tol) - 1
    seen = collections.defaultdict(set)
    new = []
    for el in lst:
        rounded = round(seen, round_digits)
        if all(abs(el - x) > tol for x in seen[rounded]):
            seen[rounded].add(el)
            new.append(el)
    return new

tol 0.01, round_digits 1. , 6.23234121 seen 6.2. 6.23246575, 6.2 , , , tol , . , , , .

O (n k), k - , . , k < n ( , , tol). , , , , , .


- ; , .

+1

All Articles