Luis Luis - 2 months ago 5
Python Question

Remove similar numbers in a list

How do I remove numbers like 86.1 and 90.1 (or 86.2 and 90.2) from the following list?

86.1 86.2 90.1 90.2

Answer

Define a threshold, iterate over the sorted numbers and add up the numbers within the threshold:

numbers = [86.1, 86.2, 90.1,90.2]

threshold = 1
numbers = iter(numbers)
amount = last = next(numbers)
count = 1
result = []
for number in sorted(numbers):
    if number - last > threshold:
        result.append(amount/count)
        amount = count = 0
    amount += number
    count += 1
    last = number

result.append(amount/count)

Comments