user16920669
user16920669

Reputation:

remove adjacent list elements based on condition?

i want remove right hand side value if difference between adjacent elements is less than 0.20, so I am doing this

a  = [183.4, 183.3 182.1, 182.75]
a  = [183.4, 182.1, 182.75] # what I want


for i, j in zip(a, a[1:]):
    if abs(i-j) <= 0.20:
        a.remove(j)
print(a) 

but the output is

[183.4, 182.75]

Upvotes: 1

Views: 238

Answers (1)

pho
pho

Reputation: 25489

Don't remove elements from a list you're iterating over. You could use a slice for both inputs of zip(): that will create a copy so you won't run into the same problem.

for i, j in zip(a[:-1], a[1:]):
    if abs(i-j) <= 0.20:
        a.remove(j)

which gives

[183.4, 182.1, 182.75]

Alternatively, invert the condition and build a new list.

a_new = a[0:1] # Create a new list with the first element of a
for i, j in zip(a, a[1:]):
    if abs(i-j) > 0.20: # Append j to the new list if the difference is greater
        a_new.append(j)

Note that this doesn't take into account the case when multiple consecutive pairs of elements are within your threshold. For example: a = [183.4, 183.3, 183.15, 182.1, 182.75], this will remove both 183.3 and 183.15.

If you want the minimum difference between consecutive elements in your result to be 0.2, simply compare with the last element of a_new and add the current element if it satisfies your condition.

a = [183.4, 183.3, 183.15, 182.1, 182.75]
a_new = a[0:1]

for i in a[1:]:
    if abs(a_new[-1] - i) > 0.2:
        a_new.append(i)

And this gives [183.4, 183.15, 182.1, 182.75]

Upvotes: 1

Related Questions