Python math.prod() 方法



Python 的 math.prod() 方法用于计算给定可迭代对象中所有元素的乘积。数学上,它表示为 -

prod(x1, x2, x3, ..., xn) = x1 × x2 × x3 × ... × xn

例如,如果我们有一个列表“[2, 3, 4, 5]”,则“math.prod([2, 3, 4, 5])”方法调用将返回 2 × 3 × 4 × 5 = 120。

语法

以下是 Python math.prod() 方法的基本语法 -

math.prod(iterable, *, start=1)

参数

此方法接受以下参数 -

  • iterable − 它是要计算其元素乘积的可迭代对象(例如列表、元组或生成器)。

  • start (可选) − 它指定乘积的起始值。其默认值为 1。

返回值

该方法返回可迭代对象中所有元素的乘积。

示例 1

在以下示例中,我们计算列表“[1, 2, 3, 4, 5]”中所有元素的乘积 -

import math
numbers = [1, 2, 3, 4, 5]
result = math.prod(numbers)
print("The result obtained is:",result)         

输出

获得的输出如下 -

The result obtained is: 120

示例 2

这里,我们使用生成器表达式生成从“1”到“5”的数字。然后我们计算这些数字的乘积 -

import math
numbers = (i for i in range(1, 6))
result = math.prod(numbers)
print("The result obtained is:",result)  

输出

以下是上述代码的输出 -

The result obtained is: 120

示例 3

现在,我们计算列表“[0.5, 0.25, 0.1]”中所有小数元素的乘积 -

import math
numbers = [0.5, 0.25, 0.1]
result = math.prod(numbers)
print("The result obtained is:",result)  

输出

我们得到如下所示的输出 -

The result obtained is: 0.0125

示例 4

在此示例中,我们计算空列表的乘积 -

import math
result = math.prod([])
print("The result obtained is:",result)  

输出

产生的结果如下所示 -

The result obtained is: 1
python_maths.htm
广告