Skip to content

Instantly share code, notes, and snippets.

@feiji110
Created April 12, 2020 04:59
Show Gist options
  • Save feiji110/b7a051f076499d0652a548e8614cdb60 to your computer and use it in GitHub Desktop.
Save feiji110/b7a051f076499d0652a548e8614cdb60 to your computer and use it in GitHub Desktop.
pythonic 函数式编程 &&nested function闭包

按照绝对值排序

def foo(x):
    return abs(x)
sorted(list1,key=foo)
list1 = [3,5,-4,-1,0,-2,-6]
list2 = sorted(list1, key=lambda x: abs(x))
print(list2)#[0, -1, -2, 3, -4, 5, -6]
print(list1)#[3, 5, -4, -1, 0, -2, -6]

闭包就是一个定义在函数内部的函数,闭包使得变量即使脱离了该函数的作用域范围也依然能被访问到。

def my_add(n):
    return lambda x : x+n # 冒号后面的表达式是函数的返回值
add_3 = my_add(3)
print(add_3(7))#10
print(add_3(6))#9 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment