Home > database >  Add or sum a value to list till condition is not valid anymore and create a new element when conditi
Add or sum a value to list till condition is not valid anymore and create a new element when conditi

Time:03-24

I got a question, I got the following code:

import numpy as np
a= [1,2,3,0,0,6,7,8,0,0,9,10,0,0]
a = np.array(a)
b=[]
c =[]

for i in a: 
    if i > 0.1:
        b.append (0.04)
    else: 
        c.append (0.04)

When I run this, I am getting

b = [0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04]
c = [0.04, 0.04, 0.04, 0.04, 0.04, 0.04]

But what I actually want is

b = [0.12, 0.12, 0.08]
c = [0.08, 0.08, 0.08]

So in b the value of 0.04 needs to be summed up till a<0.1 is reached then a new element needs to be created till when a>0.1. This needs to be repeated for whole a is reached. Same for c.

Can someone help me please.

CodePudding user response:

You were appending in the b and c array each time. You need to add 0.04 to that index until your condition is met.

import numpy as np
a= [1,2,3,0,0,6,7,8,0,0,9,10,0,0]
a = np.array(a)
b=[]
c =[]
value1 = 0
value2 = 0
index = 0;
for i in a: 
    if i > 0.1:
        value1  = 0.04
        if (value2>0):
            c.append(value2)
            value2=0
    else:
        value2  = 0.04
        if (value1 > 0):
            b.append(value1)
            value1=0
    if value1 > 0 and index==(len(a) -1):
        b.append(value1)
    if value2 > 0 and index == (len(a) - 1):
        c.append(value2)
    
    index =1
    
print(b)
print(c)
  • Related