如何将列表中的数字相乘(删除重复项后)?

时间:2012-12-05 13:29:58

标签: python

我正在使用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中的重复项后,我基本上想要将列表相乘。

2 个答案:

答案 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中,它已移至functoolsThe 2to3 handles this case

答案 1 :(得分:0)

这对你有用吗?

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