Python中有内置的product()吗?

98 投票
4 回答
104018 浏览
提问于 2025-04-17 05:18

我在看教程和书籍的时候,发现里面没有提到一个内置的乘积函数,也就是和求和函数sum()类似的那种。我找不到像prod()这样的东西。

那么,唯一能找到列表中所有项的乘积的方法就是导入mul()这个运算符吗?

4 个回答

14

从 Python 3.0 开始,reduce() 函数被移到了 functools 模块,所以你需要用不同的方法来使用它。

你可以通过 functools.reduce() 来调用这个函数:

product = functools.reduce(operator.mul, iterable, 1)

或者,如果你想遵循 Python 团队的想法(他们认为用 for 循环会更容易理解,所以去掉了 reduce()),你可以用循环来实现:

product = 1
for x in iterable:
    product *= x
19

在Python里没有叫做product的东西,但你可以这样定义它:

def product(iterable):
    return reduce(operator.mul, iterable, 1)

或者,如果你有NumPy这个库,可以使用numpy.product

130

声明

没错,Guido 拒绝了内置的 prod() 函数的想法,因为他认为这个功能很少用到。

Python 3.8 更新

在 Python 3.8 中,prod() 被加入到了数学模块中:

>>> from math import prod
>>> prod(range(1, 11))
3628800

使用 reduce() 的替代方法

正如你所提到的,使用 reduce()operator.mul() 自己实现一个并不难:

def prod(iterable):
    return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

在 Python 3 中,reduce() 函数被移到了 functools 模块,所以你需要添加:

from functools import reduce

特定情况:阶乘

顺便提一下,prod() 的主要用途是计算阶乘。我们在 数学模块 中已经有这个功能了:

>>> import math

>>> math.factorial(10)
3628800

使用对数的替代方法

如果你的数据是浮点数,你可以用 sum() 结合指数和对数来计算乘积:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

撰写回答