2013-11-23 112 views

回答

7

您可以在Python中使用reduce

>>> from operator import mul 
>>> reduce(mul, range(1, 5)) 
24 

或者,如果你有numpy,那麼最好使用numpy.prod

>>> import numpy as np 
>>> a = np.arange(1, 10) 
>>> a.prod() 
362880 
#Product along a axis 
>>> a = np.arange(1, 10).reshape(3,3) 
>>> a.prod(axis=1) 
array([ 6, 120, 504]) 
+0

謝謝!這個不起眼的建議對我很好。 – Sophie

1

在Python中沒有這樣的功能,但你可以得到列表中的所有元素的產品,採用reduce這樣

myList = [1, 2, 3] 
print reduce(lambda x, y: x * y, myList, 1)