Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to start a for loop from the end of a vector, and at the value 0 do something

I have to start looping a vector from its end to zero. When I meet the value 0 I need to replace it with the sum of the three previews values. The exception will be for the first zero met, I need just to sum the previous two values.

e.g.

v = [0, 5, 5, 0, 6, 6, 0, 7, 7 ]

Expected result:

v = [36, 5, 5, 26, 6, 6, 14, 7, 7 ]

Code

for i in range(len(v), 0):       
    if v == 0 :
        v[i] = v[i+1] + v[i+2] + v[i+3]

The code is not working. Where am I wrong?


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

1 Answer

0 votes
by (71.8m points)

You can avoid index errors with sum(v[i+1:i+4]). You have to compare each element (if v[i] == 0) not the whole list.

v = [0, 5, 5, 0, 6, 6, 0, 7, 7 ]

for i in range(len(v) - 1, -1, -1):       
    if v[i] == 0 :
        v[i] = sum(v[i+1:i+4])
print(v)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...