Compute the cumulative sum of a list until a zero appears

前端 未结 7 1142
小鲜肉
小鲜肉 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

    I would use a generator if you want performance (and it's simple too).

    def weird_cumulative_sum(seq):
        s = 0
        for n in seq:
            s = 0 if n == 0 else s + n
            yield s
    
    list_b = list(weird_cumulative_sum(list_a_))
    

    I don't think you'll get better than that, in any case you'll have to iterate over list_a at least once.

    Note that I called list() on the result to get a list like in your code but if the code using list_b is iterating over it only once with a for loop or something there is no use converting the result to a list, just pass it the generator.

提交回复
热议问题