Reduce increments in array values to 1

  • A+
Category:Languages

I am trying to create a list (say B) which increments only when there is a difference in values of another list (say A), for example:

[1,1,2,2,4,4] to [0,0,1,1,2,2] or

[1,1,1,1,4,4,4,4] to [0,0,0,0,1,1,1,1] etc.

The following code does it:

boxes=[1,1,1,1,4,4,4,4] positions=[0] position=0 for psn,box in list(enumerate(boxes))[:-1]:     if boxes[psn+1]-box ==0:         increment=0     else:         increment=1     position=position+increment     positions.append(position) print(positions) 

Can anybody give suggestions to do it using list comprehensions (preferable using lambda functions)?

 


Here's a way using nummpy:

a = [1,1,2,2,4,4] [0] + np.cumsum(np.clip(np.diff(a), 0, 1)).tolist() [0, 0, 1, 1, 2, 2] 

Or for the other example:

a = [1,1,1,1,4,4,4,4] [0] + np.cumsum(np.clip(np.diff(a), 0, 1)).tolist() [0, 0, 0, 0, 1, 1, 1, 1] 

Details

a = [1,1,2,2,4,4] 

Get the first difference of the array with np.diff

np.diff(a) array([0, 1, 0, 2, 0])  

And use np.clip to limit the values between 0 and 1:

np.clip(np.diff(a), 0, 1) array([0, 1, 0, 1, 0]) 

Finally take the np.cumsum and add a 0 at the beginning as the difference will give you an array of length n-1:

[0] + np.cumsum(np.clip(np.diff(a), 0, 1)).tolist() [0, 0, 1, 1, 2, 2] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: