2012-08-04 69 views
1

可能重複:
Returning the product of a list產品列表蟒

是否有任何其他方式來獲取列表的產物,不是這樣:

def prod(L): 
p=1 
for i in L: 
    p= i * p 
return p 

這段代碼是正確的,但我需要找到另一種方式來做到這一點。我真的找不到它。

+0

檢查發現的問題......,我不知道是不是重複的,但我沒有找到答案我需要那裏。 – Reginald 2012-08-04 10:23:43

+0

@jamylak我試了幾次,輸出是正確的。 – Reginald 2012-08-04 10:24:46

+0

@jamylak爲什麼不呢? – phant0m 2012-08-04 12:17:49

回答

8

reduce(f, iterable[, initializer])使用:

>>> from operator import mul 
>>> reduce(mul, [1, 2, 3], 1) 
6 

reduce()摘要在下面的模式: a ⊗ b ⊗ c ⊗ d ⊗ e ...其中是二進制(左結合)運算符,即,接受兩個參數的函數。

+0

這不適用於空列表。 – Dogbert 2012-08-04 10:19:14

+0

@Dogbert是的,它會,因爲初始化器給出。 – phant0m 2012-08-04 12:15:11

+1

只是注意到這個問題被標記爲「python-3.x」,而在Python 3中,「reduce」函數不是內置的。相反,它在'functools'模塊中。 – 2012-08-04 12:17:47

3
>>> reduce(lambda x, y: x * y, [1, 2, 3], 1) 
6 
>>> reduce(lambda x, y: x * y, [], 1) 
1 
1
def prod(array): 
    if len(array)==0: return 1 
    else: return array[0]*prod(array[1:]) 
4

如果你允許使用numpy

import numpy as np 
product = np.product([1, 2, 3]) # returns 1.0 if empty list