2012-12-05 24 views
2

我正在使用Python 3.2.3 IDLE。我看到有些人使用reduce命令,但由於某種原因,我沒有它。就像代碼不會出現在紫色中一樣,它會將reduce當作變量來識別。如何將列表中的數字相乘(刪除重複項後)?

這裏是我的代碼部分:

numbers = [10, 11, 11] 
numbertotal = (set(numbers)) 
#removes duplicates in my list, therefore, the list only contains [10, 11] 
print ("The sum of the list is", (sum(numbertotal))) #sum is 21 
print ("The product of the list is" #need help here, basically it should be 10 * 11 = 110 

我基本上要乘以名單後,我刪除重複的numbertotal

+0

很多信息及彼列表的產品:http://stackoverflow.com/questions/2104782/returning-the-product-of-a-list – Stuart

回答

3

reduce躲在:

from functools import reduce 

print("The product of the list is", reduce(lambda x,y:x*y, numbertotal)) 

from functools import reduce 
import operator as op 

print("The product of the list is", reduce(op.mul, numbertotal)) 

在python3它已經被移動到functoolsThe 2to3 handles this case

+0

哦沒關係。我想我得到了命令運行,但它沒有與我的代碼工作:( –

0

這是否適合您?

product = 1 
for j in numbertotal: 
    product = product * j 
print 'The product of the list is', product 
+0

像一個魅力:)謝謝你先生 –