Compute the cumulative sum of a list until a zero appears

前端 未结 7 1045
小鲜肉
小鲜肉 2021-02-01 17:52

I have a (long) list in which zeros and ones appear at random:

list_a = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1]

I want to get the list_b

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 18:49

    It doesn't have to be as complicated as made in the question asked, a very simple approach could be this.

    list_a = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1]
    list_b = []
    s = 0
    for a in list_a:
        s = a+s if a !=0 else 0
        list_b.append(s)
    
    print list_b
    

提交回复
热议问题