如何在Python中对列表元素进行数学运算?
假设我有一个数字列表 [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
基于生成器的解决方案
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
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]
1
这里提到了一种叫做“列表推导”的方法,因为这种方法总是很有趣:
>>> data = [3, 51, 34]
>>> result = [n + sum(data[:i]) for i, n in enumerate(data)]
>>> result
[3, 54, 88]
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])
3
一个简单的归约操作:
nums = [3,51,34]
reduce(lambda x, y: [y] if not x else x + [y + x[-1]], nums, None)
# [3, 54, 88]