sum()的函数是什么,但是要乘法呢?产品()? [英] What's the function like sum() but for multiplication? product()?

查看:250
本文介绍了sum()的函数是什么,但是要乘法呢?产品()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的 sum() 函数以可迭代的方式返回数字的总和.

sum([3,4,5]) == 3 + 4 + 5 == 12

我正在寻找返回产品的函数.

somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60

我很确定确实存在这样的功能,但是我找不到它.

解决方案

更新:

在Python 3.8中, prod 函数已添加到 math 模块中.请参阅: math.prod().

较旧的信息:Python 3.7和更低版本

您要查找的函数称为 prod() product(),但Python没有该函数.因此,您需要自己编写(很简单).

prod()的发音

是的,没错. Guido 拒绝了内置prod()函数的想法,因为他认为很少需要它.

reduce()的替代方案

如您所建议,使用 reduce() operator. mul() :

from functools import reduce  # Required in Python 3
def prod(iterable):
    return reduce(operator.mul, iterable, 1)

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

请注意,在Python 3中, reduce() 函数已移至 functools模块.

特殊情况:阶乘

作为附带说明, 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

请注意,使用 log()要求所有输入均为正.

Python's sum() function returns the sum of numbers in an iterable.

sum([3,4,5]) == 3 + 4 + 5 == 12

I'm looking for the function that returns the product instead.

somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60

I'm pretty sure such a function exists, but I can't find it.

解决方案

Update:

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

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

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

Alternative with reduce()

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

from functools import reduce  # Required in Python 3
def prod(iterable):
    return reduce(operator.mul, iterable, 1)

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

Note, in Python 3, the reduce() function was moved to the functools module.

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

Note, the use of log() requires that all the inputs are positive.

这篇关于sum()的函数是什么,但是要乘法呢?产品()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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