Question

I have a list like the following:

[[454.0, 82], [451.0, 82], [449.5, 82], [448.0, 82], [316.0, 82], [313.0, 82], [311.5, 82]]

I want to use list comprehension to remove items that are within 10 of each other.

Here is what I have tried so far:

>>> lst = [item for item in lst for i in range(len(lst)) if item[i+1] - item[i] > 10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> 

The above list comprehension looks like it should work, but it results in an IndexError.

Desired output:

[[454.0, 82], [316.0, 82]]

What I mean by within 10 of each other is if the absolute value of a - b is greater than 10.

I want this to return 1 value for all of the values that are within 10 of each other.

Was it helpful?

Solution

You go past the end here -- i+1 is outside the original list for the last entry:

for i in range(len(lst)) if item[i+1]

Perhaps it works if you simply do len(lst) - 1

Other way is to not use list comprehension but a normal for and check for more conditions there.

OTHER TIPS

you can do like this

a=[[454.0, 82], [451.0, 82], [449.5, 82], [448.0, 82], [316.0, 82], [313.0, 82], [311.5, 82]]
result=[]
diff=10
num=0
for i in a:
    if abs(i[0]-num)<10:
        if i[0]>num:
            result.append(i)
            num=i[0]
    else:
        result.append(i)
        num=i[0]


print result

output:[[454.0, 82], [316.0, 82]]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top