How to emulate sum() using a list comprehension?

后端 未结 11 1781
星月不相逢
星月不相逢 2020-12-05 13:24

Is it possible to emulate something like sum() using list comprehension ?

For example - I need to calculate the product of all elements in a list :

l         


        
11条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 14:10

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

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

    This:

    • Initializes a variable total to 0
    • For each item, total is incremented by the current looped item (total := total + x) via an assignment expression

提交回复
热议问题