📜  Python – math.prod() 方法

📅  最后修改于: 2022-05-13 01:55:36.617000             🧑  作者: Mango

Python – math.prod() 方法

Python中的数学模块包含许多数学运算,可以使用该模块轻松执行。 Python中的math.prod()方法用于计算给定iterable中存在的所有元素的乘积。 Python中的大多数内置容器(如列表、元组)都是可迭代的。可迭代对象必须包含数值,否则可能会拒绝非数值类型。
此方法是Python 3.8 版中的新方法。

代码 #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:如果显式指定了 start 参数

# 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:当给定的可迭代对象为空时

# 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数学库