Home > Enterprise >  Remove element from list based on condition
Remove element from list based on condition

Time:04-22

I have a list l:

l = [0.22, 0.6, 0.94, 1.28, 1.66, 2., 2.38, 2.72, 3.04, 3.42, 3.76, 4.2, 4.58, 4.94, 5.32, 5.68, 6.08, 6.42, 6.8, 7.22, 7.54]

I want to remove from the list all elements which are within a 1.00 distance to the previous element. This involves of course to stay at element i if element i 1 has been removed and check the difference between element i and element i 2 and so on. The desired output would be:

output = [0.22, 1.28, 2.38, 3.42, 4.58, 5.68, 6.8]

I obviously tried to do this with a for-loop but as this failed, I remembered that Python does not allow altering a list within a loop.

for index, i in enumerate(l[:-1]):
    j = l[index 1]
    if (j-i) < 1:
        p.remove(j)
    else:
        continue

Furthermore, I know that itertools contains the pairwise method for Python 3.10 and above, which makes it possible to calculate differences (which might be useful for this task) but I am using 3.7.6. Any solution is appreciated. Thank you!

CodePudding user response:

You could do like this:

l = [0.22, 0.6, 0.94, 1.28, 1.66, 2., 2.38, 2.72, 3.04, 3.42, 3.76, 4.2, 4.58, 
4.94, 5.32, 5.68, 6.08, 6.42, 6.8, 7.22, 7.54]
l2 = [l[0]]

for elm in l:
    if abs(elm - l2[-1]) > 1:
        l2.append(elm)

print(l2)
  • Related