我正在使用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 :(得分: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中,它已移至functools
。 The 2to3
handles this case
答案 1 :(得分:0)
这对你有用吗?
product = 1
for j in numbertotal:
product = product * j
print 'The product of the list is', product