python中math的方法_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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值