Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

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. (i.e.) 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. (i.e.) 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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...