Chichi Chichi - 1 month ago 6
Python Question

Filtering a list. Get elements of list only with a certain distance between items?

I need to get only those elements that are to some extent distant from each other. For example, I have a list of integers:

data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]


Let's assume I want to retrieve only those elements that have have a distance of at least 1000 between each other.
From the list above I need output:

[-2000, 1000, 2000, 3500, 4500, 6000]





For the moment I'm filtering this way:

filtered.append(data[0])
for index, obj in enumerate(data):
if index < (l - 1):
if abs(obj - data[index+1]) > 999:
filtered.append(data[index+1])

print(filtered)


Undesired output:

[-2000, 1000, 2000, 3500, 6000]





It fails because it compares two adjacent list elements, irregardless of the fact that some elements supposed to be filtered out and should not be taken into account when comparing.

Let me show more clearly.

Original list:
[-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]


Filtering process:

-2000 - OK
1000 - OK
2000 - OK
3500 - OK
3800 - Out
4500 - Should be OK, but it filtered out compared to 3800. But it should be compared to 3500 (not 3800 which is Out).





How to fix it?

Answer

Sorting the data and then comparing to the previous would do it:

data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]

lst = [min(data)]          # the min of data goes in solution list
for i in sorted(data[1:]):
  if i-lst[-1] > 999:      # comparing with last element
    lst.append(i)          # of the solution list

print (lst)

ouput:

[-2000, 1000, 2000, 3500, 4500, 6000]