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

南笙酒味 提交于 2019-12-02 08:23:26

a simple reduce:

nums = [3,51,34]
reduce(lambda x, y: [y] if not x else x + [y + x[-1]], nums, None)
# [3, 54, 88]

numpy.cumsum might be good choice for something like this.

In [1]: import numpy as np

In [2]: a = [3,51,34]

In [3]: np.cumsum(a)
Out[3]: array([ 3, 54, 88])

And a trivial, procedural solution, for completeness:

a = [3,51,34]

def cumsum(numbers):
  accum = 0
  result = []
  for n in numbers:
    accum += n
    result.append(accum)
  return result

print cumsum(a)

It prints [3, 54, 88]

A list comprehension approach, because that's always fun:

>>> data = [3, 51, 34]
>>> result = [n + sum(data[:i]) for i, n in enumerate(data)]
>>> result
[3, 54, 88]

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]: <generator object acc at 0x1ec9e10>

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!