為什么這段代碼列印 2?我很難理解呼叫順序以及代碼運行時會發生什么。我想知道這里發生了什么,謝謝!
代碼:
mia = lambda dan: lambda john: list(john)[dan]
john = lambda mia: lambda dan: filter(dan, map(lambda x: x % 2 1, mia))
ta = mia(-1)(john([3, 6, 9, 12, 15])(lambda f: f % 3))
print(ta)
uj5u.com熱心網友回復:
這是執行簡單任務的某種混淆方式:
- 檢查串列中的數字是奇數還是偶數,并相應地映射 1、2
- 如果這不是 3 的倍數,則過濾前一個輸出(始終為真)
- 取上一個輸出的最后一項
總之,如果輸入的最后一個數字是奇數,則輸出 2,否則輸出 1。
這可以簡化為:
list(map(lambda x: x % 2 1, [3, 6, 9, 12, 15]))[-1]
或者,保留無用的過濾器:
list(filter(lambda f: f % 3, map(lambda x: x % 2 1, [3, 6, 9, 12, 15])))[-1]
這是使用函式式方法,其中函式回傳函式而不是值。此外,區域變數的名稱被設計為令人困惑(miain與函式john無關)mia
有趣的mia是,相當于operator.itemgetter
uj5u.com熱心網友回復:
它做的比看起來要少得多。
為簡化起見,將 lambda 運算式轉換為def陳述句。
def mia(dan):
def inner(john):
lst = list(john)
return lst[dan]
return inner
def john(mia):
def inner(dan):
mp = map(lambda x: x % 2 1, mia)
return filter(dan, mp)
return inner
為了進一步簡化,分離你的函式呼叫。
# just return the inner function
john_inner_func = john([3, 6, 9, 12, 15])
# first map element % 2 1 to each element of the given array
# this results in [2, 1, 2, 1, 2]
# next it filters all truthy (non-zero) values of the result of element % 3.
# Since all are positive and less than 3 the result is the same
# [2, 1, 2, 1, 2]
john_filter_result = john_inner_func(lambda f: f % 3)
# just return the inner function
mia_inner_func = mia(-1)
# return the -1 index of the filter result as a list
# this gives the last element, or 2
ta = mia_inner_func(john_filter_result)
print(ta)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410032.html
標籤:
