Python中是否有内置product()? [英] Is there a built-in product() in Python?

查看:88
本文介绍了Python中是否有内置product()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览教程和书籍,但是找不到内置产品函数,即与sum()相同类型的产品,但是找不到诸如prod()之类的东西.

是导入mul()运算符可以在列表中找到商品的唯一方法吗?

解决方案

发音

是的,没错. 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

I've been looking through a tutorial and book but I can find no mention of a built in product function i.e. of the same type as sum(), but I could not find anything such as prod().

Is the only way I could find the product of items in a list by importing the mul() operator?

解决方案

Pronouncement

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Python 3.8 Update

In Python 3.8, prod() was added to the math module:

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

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

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

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

In Python 3, the reduce() function was moved to the functools module, so you would need to add:

from functools import reduce

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

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

这篇关于Python中是否有内置product()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆