how can i do math operation on list elements in python?

后端 未结 5 1820
北恋
北恋 2021-01-28 03:36

Suppose i have list of numbers [3, 51, 34]. I want to add to each element the sum of the previous elements and return a new list with these new values. So here the

5条回答
  •  有刺的猬
    2021-01-28 04:24

    And a trivial, procedural solution, for completeness:

    a = [3,51,34]
    
    def cumsum(numbers):
      accum = 0
      result = []
      for n in numbers:
        accum += n
        result.append(accum)
      return result
    
    print cumsum(a)
    

    It prints [3, 54, 88]

提交回复
热议问题