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