當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python math.prod()用法及代碼示例


數學模塊Python中的Math庫包含許多數學運算,可以使用該模塊輕鬆執行。math.prod()Python中的方法用於計算給定可迭代對象中所有元素的乘積。 Python中的大多數內置容器(例如list,tuple)都是可迭代的。迭代器必須包含數字值,否則可能會拒絕非數字類型。此方法是Python版本3.8中的新增函數。

用法: math.prod(iterable, *, start = 1)

參數:
iterable:包含數字值的可迭代
start:代表起始值的整數。 start是一個命名(僅關鍵字)參數,其默認值為1。


返回:給定可迭代項中所有元素的計算結果。

代碼1:用於math.prod()方法

# Python Program to explain math.prod() method 
  
# Importing math module 
import math 
  
# list 
arr = [1, 2, 3, 4, 5] 
  
# Calculate the product of 
# of all elements present 
# in the given list 
product = math.prod(arr) 
print(product) 
  
  
# tuple 
tup = (0.5, 0.6, 0.7) 
  
# Calculate the product  
# of all elements present 
# in the given tuple 
product = math.prod(tup) 
print(product) 
  
  
# range 
seq = range(1, 11) 
  
# Calculate the product  
# of all elements present 
# in the given range 
product = math.prod(seq) 
print(product) 
  
# As the start value is not specified  
# it will default to 1
輸出:
120
0.21
3628800

代碼2:如果明確指定了啟動參數

# Python Program to explain math.prod() method 
  
# Importing math module 
import math 
  
  
# By default start value is 1 
# but can be explicitly provided 
# as a named (keyword-only) parameter 
  
# list 
arr = [1, 2, 3, 4, 5] 
  
# Calculate the product of 
# of all elements present 
# in the given list 
product = math.prod(arr, start = 2) 
print(product)
輸出:
240

代碼3:當給定的Iterable為空時

# Python Program to explain math.prod() method 
  
# Importing math module 
import math 
  
# If the given input iterable 
# is empty, then this method 
# returns the start value  
  
# list 
arr = [] 
  
# Calculate the product of 
# of all elements present 
# in the given list 
product = math.prod(arr) 
print(product) 
  
  
# Tuple 
tup = () 
  
# Calculate the product of 
# of all elements present 
# in the given tuple 
product = math.prod(tup, start = 5) 
print(product)
輸出:
1
5

參考: Python math library



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python – math.prod() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。