数学模块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 set()用法及代码示例
- Python os.dup()用法及代码示例
- Python next()用法及代码示例
- Python PIL Image.new()用法及代码示例
- Python sys.getswitchinterval()用法及代码示例
- Python os.getppid()用法及代码示例
- Python sympy.rf()用法及代码示例
- Python os.ctermid()用法及代码示例
- Python PIL BoxBlur()用法及代码示例
- Python sympy RGS用法及代码示例
- Python os.times()用法及代码示例
- Python os.abort()用法及代码示例
- Python os.WEXITSTATUS()用法及代码示例
- Python os._exit()用法及代码示例
注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python – math.prod() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。