Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 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]
question from:https://stackoverflow.com/questions/65661345/python-add-list-items-with-condition

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

1 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...