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

4

2 回答 2

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. 处理这个2to3案子

于 2012-12-05T13:31:25.793 回答
0

这对你有用吗?

product = 1
for j in numbertotal:
    product = product * j
print 'The product of the list is', product
于 2012-12-05T13:33:02.253 回答