Reputation: 440
I have a Python list.
x = [230, 235, 300, 480, 480, 506, 515, 516]
I want to print a list with elements from Array x, with difference of more than a value(lets assume 10). So the new list will contain only elements with difference of more than 10 than the next element. The output list should contain elements which have more than 10 difference with their adjacent element in the given list. Output should be a list of [230, 300, 480, 516]
I want to make a function to make this possible.
b = [0] + x
t = []
for i in range(len(b)-1):
if(b[i+1]-b[i]>10):
t.append(b[i])
print(t)
I tried this. But I'm not getting proper output.
Upvotes: 1
Views: 736
Reputation: 69
You can try this:
a=[230,235,300,480,480,506,515,516]
b=[0]+a
c=[]
for i in range(0,len(b)-1):
if((b[i+1]-b[i])>10):
c.append(b[i+1])
print(c)
Output:
[230, 300, 480, 506]
Upvotes: 1
Reputation: 42718
Using iterators:
import itertools
def gapFilter(l, gap_value):
it1, it2 = itertools.tee(l)
next(it2)
return [x for x, y in zip(it1, it2) if abs(x-y) >= gap_value]
Here you have the live example
For getting the initial 0, just append it to the list before computing.
Python3
example:
gapFilter([0, *x], 10)
Upvotes: 0
Reputation: 579
Using numpy
:
import numpy as np
xarr = np.array(x)
result = xarr[np.where(np.diff(xarr) > 10)[0]+1]
Produces:
array([300, 480, 506])
I believe this may be what you are looking for?
Upvotes: 1
Reputation: 71580
Try this:
print([k for k,v in zip(x, x[1:]) if abs(k-v) > 10])
zip
is your friend.
Note: this works even with the list having up and down values (meaning some times large number, and sometimes small), because i use abs
.
Update:
l=[(k,v) for k,v in zip(x[1:], x) if abs(k-v) >= 10]
print([list(zip(*l))[1][0]]+list(list(zip(*l))[0]))
Works to get desired output, it's your friend now.
Upvotes: 0