Python中有内置的product()吗?

2024-05-12 18:56:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我看了一本教程和一本书,但是没有提到内置的产品函数,即sum()的类型,但是我找不到诸如prod()之类的东西。

是通过导入mul()运算符来查找列表中项的乘积的唯一方法吗?


Tags: 方法函数类型列表产品运算符教程prod
3条回答

宣告

是的,没错。内置prod()函数的Guidorejected the idea,因为他认为很少需要它。

Python 3.8更新

在Python3.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 module,因此需要添加:

from functools import reduce

具体情况:阶乘

顺便说一下,prod()的主要动机用例是计算阶乘。我们已经在math module中对此提供了支持:

>>> 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

自从reduce() function has been moved to the module ^{} python 3.0以来,您必须采取不同的方法。

您可以使用functools.reduce()访问函数:

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

或者,如果您想遵循python团队的精神(他们删除了reduce(),因为他们认为for更具可读性),请使用循环:

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

Python中没有product,但是可以将其定义为

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

或者,如果您有NumPy,请使用numpy.product

相关问题 更多 >