Elegant pythonic cumsum

前端 未结 10 1114
-上瘾入骨i
-上瘾入骨i 2020-12-16 11:54

What would be an elegant and pythonic way to implement cumsum?
Alternatively - if there\'a already a built-in way to do it, that would be even better of course...

10条回答
  •  眼角桃花
    2020-12-16 12:28

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can use and increment a variable within a list comprehension:

    total = 0
    [total := total + x for x in [1, 2, 3 ,4, 5]]
    # [1, 3, 6, 10, 15]
    

    This:

    • Initializes a variable total to 0 which symbolizes the cumulative sum
    • For each item, this both:
      • increments total with the current looped item (total := total + x) via an assignment expression
      • and at the same time, maps x to the new value of total

提交回复
热议问题