How to emulate sum() using a list comprehension?

后端 未结 11 1763
星月不相逢
星月不相逢 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:02
    >>> reduce(int.__mul__,[1,2,3])
    6
    
    C:\Users\Henry>python -m timeit -s "" "reduce(int.__mul__,range(10000))" 
    1000 loops, best of 3: 910 usec per loop
    
    C:\Users\Henry>python -m timeit -s "from operator import mul" "reduce(mul,range(10000))"
    1000 loops, best of 3: 399 usec per loop
    
    C:\Users\Henry>
    
    0 讨论(0)
  • 2020-12-05 14:05

    It is possible to achieve by using lambda with list comprehension Since we can't assign a value in list comprehension we go with lambda

    Solution:

    >>> (lambda number_list, sum=0:[sum for number in number_list for sum in [sum + number]][-1])([1, 2, 3, 4, 5])
    >>> 15
    
    0 讨论(0)
  • 2020-12-05 14:06

    I might be a bit late for this discussion, but I would like to mention that list comprehentions are turing complete, and thus this can be done with a list comprehention!

    This however is messy, so I have used the following trick, which makes a cummulative array, and returns the last element

    def sum(l):
        return [c[-1] for c in [[0]] for e in l if c.append(c[-1] + e) is None][-1]
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-05 14:10

    Something like this:

    >>> a = [1,2,3]
    >>> reduce(lambda x, y: x*y, a)
    6
    
    0 讨论(0)
提交回复
热议问题