使用列表理解(或其他緊湊方法)來複制此簡單函數的最佳方法是什麼?帶累加器的列表理解
import numpy as np
sum=0
array=[]
for i in np.random.rand(100):
sum+=i
array.append(sum)
使用列表理解(或其他緊湊方法)來複制此簡單函數的最佳方法是什麼?帶累加器的列表理解
import numpy as np
sum=0
array=[]
for i in np.random.rand(100):
sum+=i
array.append(sum)
在Python 3,你會使用itertools.accumulate()
:
from itertools import accumulate
array = list(accumulate(rand(100)))
累加得到相加的值的輸入的迭代,從所述第一值的運行結果:
>>> from itertools import accumulate
>>> list(accumulate(range(10)))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
您可以傳入另一個操作作爲第二個參數;這應該是一個可以調用的累加結果和下一個值,返回新的累計結果。 operator
module在爲這類工作提供標準數學運算符方面非常有幫助;你可以用它來製作一個正在運行的乘法結果,例如:
>>> import operator
>>> list(accumulate(range(1, 10), operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
的功能是很容易反向移植到舊版本(Python 2中,或Python 3.0或3.1):
# Python 3.1 or before
import operator
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
total = next(it)
yield total
for element in it:
total = func(total, element)
yield total
既然你「已經在使用numpy
,您可以使用cumsum
:
>>> from numpy.random import rand
>>> x = rand(10)
>>> x
array([ 0.33006219, 0.75246128, 0.62998073, 0.87749341, 0.96969786,
0.02256228, 0.08539008, 0.83715312, 0.86611906, 0.97415447])
>>> x.cumsum()
array([ 0.33006219, 1.08252347, 1.7125042 , 2.58999762, 3.55969548,
3.58225775, 3.66764783, 4.50480095, 5.37092001, 6.34507448])
好吧,你說你不想numpy
但這裏是我的解決方案呢。 在我看來,你只是採取累計總和,因此使用cumsum()
函數。
import numpy as np
result = np.cumsum(some_array)
對於隨機例如
result = np.cumsum(np.random.uniform(size=100))
是否使用numpy的任何機會 ?我知道numpy對於這樣的事情有很好的功能。 – arshajii
我不會使用列表理解 - 元素期望彼此獨立,在這種情況下,他們不是。 – Izkata
爲什麼你想把它變成一個列表理解?將它保存在一個單獨的循環中可讀性更強。或者,可以將它設爲'array = [0]','for rand in(100):array.append(i + array [-1])'。 –