亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:Reduce() 和函數作為函數的參數

Python:Reduce() 和函數作為函數的參數

一只甜甜圈 2022-10-25 14:57:38
在 Python3 中,我試圖弄清楚 reduce() 和函數作為函數的參數,或者更好地將函數作為另一個函數的參數傳遞,其中第一個函數不明確,見下文給定:# define a function `call` where you provide the function and the argumentsdef call(y,f):    return f(y)# define a function that returns the squaresquare = lambda x : x*x# define a function that returns the incrementincrement = lambda x : x+1# define a function that returns the cubecube = lambda x : x*x*x# define a function that returns the decrementdecrement = lambda x : x-1# put all the functions in a list in the order that you want to execute themfuncs = [square, increment, cube, decrement]#bring it all together. Below is the non functional part. #in functional programming you separate the functional and the non functional parts.from functools import reduce # reduce is in the functools libraryprint(reduce(call, funcs,1)) # output 7 , 2  res 124為什么它不起作用我改變def call(y,f)       f(y)在def call(f,y)       f(y)并給出一個錯誤:................py", line 27, in call    return f(y)TypeError: 'int' object is not callable
查看完整描述

1 回答

?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

functools.reduce()

要理解這一點,我們首先應該了解它是如何reduce工作的,reduce 需要 3 個參數:

  • 一個函數

  • 可迭代元素

  • 一個初始化器。

讓我們關注函數和可迭代元素來了解函數是如何調用的

下面是functools的官方文檔:

functools.reduce(function, iterable[, initializer])

將兩個參數的函數從左到右累積應用于iterable的項目,以將iterable減少為單個值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 計算 ((((1+2)+3)+4)+5)。左邊的參數 x 是累積值,右邊的參數 y 是迭代的更新值。如果存在可選的初始值設定項,則在計算中將其放置在可迭代項之前,并在可迭代項為空時用作默認值。如果沒有給出初始化程序并且可迭代只包含一個項目,則返回第一個項目。

大致相當于:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)    if initializer is None:
        value = next(it)    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value


在這里你可以理解,它接受第一個參數中傳遞的函數,并以 value、element 作為傳遞函數的參數來執行它。請注意,元素是 eachelement在第二個參數iterable中。所以當你打電話時reduce(call, funcs, 1),

發生以下情況:由于初始化程序=1,值=初始化程序,

對于 funcs 中的每個 func,發生了以下情況

調用(1,函數)

TLDR; 當您替換 y 和 f 時,您正在嘗試調用 1(func),這是不可能的,這就是第一個初始解決方案有效的原因,因為它調用了 func(1)

參考:Python Docs - functools


查看完整回答
反對 回復 2022-10-25
  • 1 回答
  • 0 關注
  • 242 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號