How to find the cumulative sum of numbers in a list?

前端 未结 21 1639
挽巷
挽巷 2020-11-22 02:09
time_interval = [4, 6, 12]

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

21条回答
  •  再見小時候
    2020-11-22 03:02

    If You want a pythonic way without numpy working in 2.7 this would be my way of doing it

    l = [1,2,3,4]
    _d={-1:0}
    cumsum=[_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]
    

    now let's try it and test it against all other implementations

    import timeit, sys
    L=list(range(10000))
    if sys.version_info >= (3, 0):
        reduce = functools.reduce
        xrange = range
    
    
    def sum1(l):
        cumsum=[]
        total = 0
        for v in l:
            total += v
            cumsum.append(total)
        return cumsum
    
    
    def sum2(l):
        import numpy as np
        return list(np.cumsum(l))
    
    def sum3(l):
        return [sum(l[:i+1]) for i in xrange(len(l))]
    
    def sum4(l):
        return reduce(lambda c, x: c + [c[-1] + x], l, [0])[1:]
    
    def this_implementation(l):
        _d={-1:0}
        return [_d.setdefault(idx, _d[idx-1]+item) for idx,item in enumerate(l)]
    
    
    # sanity check
    sum1(L)==sum2(L)==sum3(L)==sum4(L)==this_implementation(L)
    >>> True    
    
    # PERFORMANCE TEST
    timeit.timeit('sum1(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
    >>> 0.001018061637878418
    
    timeit.timeit('sum2(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
    >>> 0.000829620361328125
    
    timeit.timeit('sum3(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
    >>> 0.4606760001182556 
    
    timeit.timeit('sum4(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
    >>> 0.18932826995849608
    
    timeit.timeit('this_implementation(L)','from __main__ import sum1,sum2,sum3,sum4,this_implementation,L', number=100)/100.
    >>> 0.002348129749298096
    

提交回复
热议问题