新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python中Operator計算函數(shù)
使用 operator 模塊中的 mul 函數(shù)來實現(xiàn)階乘:

成都創(chuàng)新互聯(lián),專注為中小企業(yè)提供官網(wǎng)建設、營銷型網(wǎng)站制作、成都響應式網(wǎng)站建設、展示型成都做網(wǎng)站、網(wǎng)站建設、外貿(mào)營銷網(wǎng)站建設等服務,幫助中小企業(yè)通過網(wǎng)站體現(xiàn)價值、有效益。幫助企業(yè)快速建站、解決網(wǎng)站建設與網(wǎng)站營銷推廣問題。
from operator import mul def factWithMul(n): return reduce(mul, range(1, n + 1))
相對來說,在Operator模塊中使用計算功能,使得代碼更加簡潔。
從源代碼分析,mul函數(shù)是計算兩個參數(shù)的乘積。
def mul(a, b): "Same as a * b." return a * b
拓展使用 lambda 方式來實現(xiàn):
from functools import reduce def fact(n): return reduce(lambda a, b: a * b, range(1, n + 1))
這里使用的是reduce方法。函數(shù)函數(shù)有兩個參數(shù)。reduce()函數(shù)對集合中的第一個和第二個元素進行函數(shù)處理,然后對帶有第三個元素的結果進行函數(shù)處理,最終得到一個結果。
以上就是python中Operator計算函數(shù)的方法,希望能對大家有所幫助!
當前名稱:創(chuàng)新互聯(lián)Python教程:Python中Operator計算函數(shù)
文章轉(zhuǎn)載:http://fisionsoft.com.cn/article/dhohssg.html


咨詢
建站咨詢
