2013-11-23 45 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)