python當中的坑【閉包與lambda】

來源:互聯網
上載者:User

標籤:參數   oca   global   ret   print   產生   遍曆   enc   現象   

先來看一個栗子:

def create():    return [lambda x:i*x for i in range(5)]for i in create():    print(i(2))

結果:

88888

create函數的傳回值時一個列表,列表的每一個元素都是一個函數 -- 將輸入參數x乘以一個倍數i的函數。預期的結果時0,2,4,6,8. 但結果是5個8,意外不意外。

由於出現這個陷阱的時候經常使用了lambda,所以可能會認為是lambda的問題,但lambda表示不願意背這個鍋。問題的本質在與python中的屬性尋找規則,LEGB(local,enclousing,global,bulitin),在上面的例子中,i就是在閉包範圍(enclousing),而Python的閉包是 遲綁定 , 這意味著閉包中用到的變數的值,是在內建函式被調用時查詢得到的

 解決辦法也很簡單,那就是變閉包範圍為局部範圍。

def create():    return [lambda x, i=i:i*x for i in range(5)]for i in create():    print(i(2))

換種寫法:

def create():    a = []    for i in range(5):        def demo(x):            return x*i        a.append(demo)    return afor i in create():    print(i(2))

以上兩種寫法是一樣的

結果:

02468

  ---_<_>_---

再來一個問題相似的栗子

代碼很簡單:(聲明:python3問題)

nums = range(2,20)for i in nums:    nums = filter(lambda x: x==i or x%i, nums)print(list(nums))

同樣也有另外一種寫法

def create():    a = []    for i in range(5):        def demo(x,i=i):            return x*i        a.append(demo)    return afor i in create():    print(i(2))

結果:

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

同樣按照正常的邏輯結果應該為:

[2, 3, 5, 7, 11, 13, 17, 19]

問題產生的原因:

  • 在python3當中filter()函數返回的是一個迭代器,因此並沒有做真正的執行,而是在每次調用的時候執行(python2中filter()返回的值列表,無此現象)
  • 在遍曆後執行列印時,現在執行迴圈當中的函數,同上面一個栗子的問題,i這個變數使用的是最後調用時的值,與以上栗子不同的是以上栗子用的是內嵌範圍的值,而這個栗子用的是全域i的值

修改代碼:

nums = range(2,20)for i in nums:    nums = filter(lambda x,i=i: x==i or x%i, nums)print(list(nums))

結果:

[2, 3, 5, 7, 11, 13, 17, 19]

  更多精彩點擊查看---_<_>_---

python當中的坑【閉包與lambda】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.