Compute the cumulative sum of a list until a zero appears

前端 未结 7 1041
小鲜肉
小鲜肉 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:45

    You are playing with the indices too much in the code you posted when you do not really have to. You can just keep track of a cumulative sum and reset it to 0 every time you meet a 0.

    list_a = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1]
    
    cum_sum = 0
    list_b = []
    for item in list_a:
        if not item:            # if our item is 0
            cum_sum = 0         # the cumulative sum is reset (set back to 0)
        else:
            cum_sum += item     # otherwise it sums further
        list_b.append(cum_sum)  # and no matter what it gets appended to the result
    print(list_b)  # -> [1, 2, 3, 0, 1, 2, 0, 1, 0, 1, 2, 3]
    

提交回复
热议问题