List comprehension for running total

前端 未结 13 1341
感动是毒
感动是毒 2020-12-05 02:47

I want to get a running total from a list of numbers.

For demo purposes, I start with a sequential list of numbers using range

a = range         


        
相关标签:
13条回答
  • 2020-12-05 03:41

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

    # items = range(7)
    total = 0
    [(x, total := total + x) for x in items]
    # [(0, 0), (1, 1), (2, 3), (3, 6), (4, 10), (5, 15), (6, 21)]
    

    This:

    • Initializes a variable total to 0 which symbolizes the running sum
    • For each item, this both:
      • increments total by the current looped item (total := total + x) via an assignment expression
      • and at the same time returns the new value of total as part of the produced mapped tuple
    0 讨论(0)
提交回复
热议问题