sum()的功能是什么,但乘法?产品()?

问题描述 投票:166回答:8

Python的sum()函数返回迭代中的数字之和。

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

我正在寻找返回产品的功能。

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

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

python product built-in pep
8个回答
201
投票

实际上,Guido否决了这个想法:http://bugs.python.org/issue1093

但是,如该问题所述,您可以轻松制作一个:

from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator

reduce(operator.mul, (3, 4, 5), 1)

42
投票

Update:

在Python 3.8中,prod函数被添加到math模块中。见:math.prod()

旧信息:Python 3.7及之前版本

您正在寻找的函数将被称为prod()或product(),但Python没有该函数。所以,你需要自己编写(这很容易)。

在prod()上发音

恩,那就对了。 Guido rejected the idea是一个内置的prod()函数,因为他认为很少需要它。

替代reduce()

如你所知,使用reduce()operator.mul()制作自己并不难:

from functools import reduce
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

注意,使用log()要求所有输入都是正数。


40
投票

没有一个内置,但它很容易滚动自己,如here所示:

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

查看此问题的答案:

Which Python module is suitable for data manipulation in a list?


35
投票

在numpy中有一个prod()可以满足您的要求。


22
投票
Numeric.product 

( 要么

reduce(lambda x,y:x*y,[3,4,5])

)


16
投票

用这个

def prod(iterable):
    p = 1
    for n in iterable:
        p *= n
    return p

由于没有内置的prod功能。


2
投票

我更喜欢使用a和使用bfunctools.reduce()上面的answernumpy.prod()答案,但这里是使用itertools.accumulate()的另一个解决方案:

import itertools
import operator
prod = list(itertools.accumulate((3, 4, 5), operator.mul))[-1]

1
投票

也许不是“内置”,但我认为它是内置的。无论如何只是使用numpy

import numpy 
prod_sum = numpy.prod(some_list)
© www.soinside.com 2019 - 2024. All rights reserved.