Python 中有内置的 product()吗?

我一直在查看一个教程和一本书,但是我没有发现任何内置的产品函数,即与 sum ()类型相同的类型,但是我找不到任何类似于 prod()的东西。

只有通过导入 mul()操作符才能找到列表中项的产品吗?

91088 次浏览

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

There is no product in Python, but you can define it as

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

Or, if you have NumPy, use numpy.product.

from numpy import multiply, product
list1 = [2,2,2]
list2 = [2,2,2]
mult = 3
prod_of_lists = multiply(list1,list2)
>>>[4,4,4]
prod_of_list_by_mult = multiply(list1,mult)
>>>[6,6,6]
prod_of_single_array = product(list1)
>>>8

numpy has many really cool functions for lists!

Since the reduce() function has been moved to the module functools python 3.0, you have to take a different approach.

You can use functools.reduce() to access the function:

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

Or, if you want to follow the spirit of the python-team (which removed reduce() because they think for would be more readable), do it with a loop:

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