我如何在python中的列表元素上进行数学运算?

时间:2014-04-18 14:45:22

标签: python list loops operations

假设我有数字列表[3, 51, 34]。我想向每个元素添加前面元素的总和,并返回包含这些新值的新列表。 所以这里的结果是[3, 54, 88]。如何在任意大小的输入列表上执行此操作?此代码的最后一行应该适用于已知的大小列表。

indices1 = range(len(list1))

indices1.sort(key=lambda x: list2[x])
list1 = map(lambda i: list1[i], indices1)
labelled = zip(list1, ascii_uppercase)
sorted_data = sorted(labelled, key=itemgetter(0)) 

labels = [pair[1] for pair in sorted_data]
newlist, = [ 0, list1[0], list1[1] + list1[2], list1[0] + list[1] + list[2]]

5 个答案:

答案 0 :(得分:3)

numpy.cumsum可能是这样的好选择。

In [1]: import numpy as np

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

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

答案 1 :(得分:3)

简单的简化:

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

答案 2 :(得分:0)

完整性是一个微不足道的程序性解决方案:

a = [3,51,34]

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

print cumsum(a)

打印[3, 54, 88]

答案 3 :(得分:0)

列表理解方法,因为它总是很有趣:

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

答案 4 :(得分:0)

基于生成器的解决方案

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]

因为它将是最快的一个:

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