0

I'd like to have an array of values, a threshold and then a for loop. I'd like the for loop to look at the ith value and the ith+1 value in the array at the same time and perform an action if they are BOTH above the threshold, else assign a 0 value if they are not. The intention is to apply to a signal in order to catch the signal and not random noise spikes.

Have tried the following, where the final 7 in the array is an unwanted value:

array = [1,2,7,6,3,2,3,8,6,4,7,2,3,]
larray = array[0:len(array)-1]
rarray = array[1:len(array)]
threshold = 5
output = []

for i, j in [larray, rarray]:
    if i and j > threshold:
        new.append(i)
        new.append(j)
    else:
        new.append(0)

Am expecting the output to be: output = [0,0,7,6,0,0,0,8,6,0,0,0]

Leon B
  • 1
  • You most certainly meant `if i > threshold and j > threshold:`, the condition as you wrote effectively evaluates as `(i) and (j > threshold)`. – metatoaster Feb 09 '23 at 00:24
  • Also, `for i, j in [larray, rarray]:` makes no sense; you presumably want `for i, j in zip(larray, rarray):`. And the slices could simplify to `larray = array[:-1]` and `rarray = array[1:]`. – ShadowRanger Feb 09 '23 at 00:29
  • @metatoaster: Or for needlessly complicated fun with Python chained comparisons, `if i > threshold < j:`. :-) – ShadowRanger Feb 09 '23 at 00:30
  • @ShadowRanger o_O \*twitch\* (yes it works but don't actually chain that, to all other readers because good lord that is non-intuitive for non Python programmers or users of languages that allow that type of operator chaining) – metatoaster Feb 09 '23 at 00:34
  • @metatoaster: I *did* say it was needlessly complicated fun. :-) And yeah, while I appreciate chained comparisons for some constructs (e.g. a range check like `if lowerbound < value < upperbound:` or a "everything's the same" check like `if a == b == c:`), I'd only ever break out that horrible "two only semi-related comparisons for the price of one" nonsense for code golfing. – ShadowRanger Feb 09 '23 at 00:39
  • Thank you all, I've used bits and pieces from all of your recommendations to some effect. – Leon B Feb 09 '23 at 01:06

0 Answers0