2013-11-26 37 views
8

使用列表理解(或其他緊湊方法)來複制此簡單函數的最佳方法是什麼?帶累加器的列表理解

import numpy as np 

sum=0 
array=[] 
for i in np.random.rand(100): 
    sum+=i 
    array.append(sum) 
+0

是否使用numpy的任何機會 ?我知道numpy對於這樣的事情有很好的功能。 – arshajii

+1

我不會使用列表理解 - 元素期望彼此獨立,在這種情況下,他們不是。 – Izkata

+1

爲什麼你想把它變成一個列表理解?將它保存在一個單獨的循環中可讀性更強。或者,可以將它設爲'array = [0]','for rand in(100):array.append(i + array [-1])'。 –

回答

6

在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 
+0

這一個工程,但我正在尋找像緊湊使用列表理解 - 就像在ipython命令行上。 – Pierz

+0

@Pierz:我在'accumulate()'迭代器上使用'list()'來給你一個值的快速列表。你仍然可以在列表理解中使用它,'[v for accumulate(rand(100))]';你不能用*只是*列表理解來做這件事,然而,因爲你沒有權限訪問到目前爲止產生的前一個元素。 –

+0

這是一個很好的方法,但我不確定是否有一個簡單的方法可以在列表理解中獲得累計總和。同意這可能不是最佳做法,但在命令行上工作時,使用緊湊形式很方便。 – Pierz

4

既然你「已經在使用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]) 
1

好吧,你說你不想numpy但這裏是我的解決方案呢。 在我看來,你只是採取累計總和,因此使用cumsum()函數。

import numpy as np 
result = np.cumsum(some_array) 

對於隨機例如

result = np.cumsum(np.random.uniform(size=100))