how can i do math operation on list elements in python?

后端 未结 5 1823
北恋
北恋 2021-01-28 03:36

Suppose i have list of numbers [3, 51, 34]. I want to add to each element the sum of the previous elements and return a new list with these new values. So here the

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-28 04:11

    generator based solution

    In [25]: ll = [3,51,34]
    
    In [26]: def acc(myiter):                                                                                                                                   
       ....:     it = iter(myiter)
       ....:     total = it.next()
       ....:     yield total
       ....:     for element in it:
       ....:         total = total + element                                                                                                                    
       ....:         yield total
       ....: 
    
    In [27]: acc(ll)
    Out[27]: 
    
    In [28]: [x for x in acc(ll)]                                                                                                                               
    Out[28]: [3, 54, 88]
    

    as it will be the fastest one:

    In [29]: %timeit [x for x in acc(ll)]
    1000000 loops, best of 3: 1.26 µs per loop
    
    In [30]: import numpy as np
    
    In [31]: np.cumsum(ll)                                                                                                                                      
    Out[31]: array([ 3, 54, 88])
    
    In [32]: %timeit np.cumsum(ll)
    100000 loops, best of 3: 15.8 µs per loop
    
    In [33]: %timeit reduce(lambda x, y: [y] if not x else x + [y + x[-1]], ll, None)                                                                           
    1000000 loops, best of 3: 1.87 µs per loop                                                                                                                  
    
    In [34]: %timeit  [n + sum(ll[:i]) for i, n in enumerate(ll)]                                                                                               
    100000 loops, best of 3: 1.99 µs per loop 
    

提交回复
热议问题