简体   繁体   中英

Python add list items with condition

I have a scenario like this:

main = [200,300,400,500]
sec = [0,0,1,0]
new = []

The condition is,

  1. if element in the second list is equal to 0, then add the element in first list. (ie) the element in the sec list is 0, so then the element in the main have to be like 500(200+300).
  2. if element in the second list is equal to 1,then in the first list place the above element down. (ie) the element in the first list is 1, so then the element in the main have to the same as previous.

output has to be like,

new = [200,500,500,900]

For given conditions and constraints this works fine

main = [200,300,400,500]
sec = [0,0,1,0]
new = []

j=0
for i in sec:
    if  i==0 and len(new)!=0:
         new.append(new[-1]+main[j])
         j+=1
    elif i==0 and len(new)==0:
         new.append(main[j])
         j+=1
    elif i==1:
         new.append(new[-1])
print(new)
       
main = [200,300,400,500]
sec = [0,0,1,0]
new = [main[0]]

for i in range(1, len(main)):
    if sec[i]:
        new.append(new[-1])
    else:
        new.append(main[i] + main[i - 1])
        
print(new)

How about:

main = [200,300,400,500]
sec = [0,0,1,0]
mem = 0
new = [main[0]]
for idx in range(1,len(main)):
    mem = mem if sec[idx] else sum(main[idx-1: idx+1])
    new.append(mem)
new
[200, 500, 500, 900]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM