python-匿名函數

匿名函數 

匿名函數就是沒有名字,就是不須要顯示的指定函數。ide

#未匿名
def func(x,y,z=1):
    return x+y+z 
print(func(11,22))

#匿名後
lambda x,y,z=1:x+y+z

func = lambda x,y,z=1:x+y+z
func(1,2,3)
View Code

1、匿名函數的應用:函數

 1 #列表
 2 nums = [11,99,88,67,23,2,37,5]
 3 nums.sort()#從小到大排序
 4 nums.sort(reverse=True)#從打到小排序
 5 nums.reverse() #反正列表 
 6 
 7 #列表嵌套字典
 8 infors  = [
 9     {"name":"alex","age":28},
10     {"name":"smith","age":18}
11     {"name":"Jones","age":19}
12 ]
13 infors.sort(key=lambda x:x["name"]) #以name爲例的按ASCII排序
14 print(infors)
View Code

2、匿名函數當作實參spa

1 def test(a,b,func):
2     result = func(a,b)
3     return result
4 num = test(11,22,lambda x,y:x+y)
5 print(num)
View Code

3、匿名函數動態化code

1 def test(a,b,func):
2     result = func(a,b)
3     return result 
4 func_new = input("請輸入一個匿名函數:")
5 #此時屬於的「匿名函數」非真正的函數,獲得的只是一個字符串,eg. "lambda x,y:x+y"。字符串是帶雙引號或單引號的。
6 func_new = eval(func_new) #去掉字符串的引號
7 num = test(11,22,func_new)
8 print(num)
View Code

 

  • 知識補充點:

num+=num 與 num = num + numblog

 1 #不可變數據類型
 2 a = 100
 3 
 4 def test(num):
 5     num+=num
 6     print(num)
 7 test(a)
 8 print(a)
 9 ------------
10 200
11 100 
12 
13 #可變數據類型
14 a = [100]
15 def test(num):
16     num+=num #===>[100]+[100] = [100,100]
17     print(num) 
18 test(a)
19 print(a)
20 ------------
21 [100, 100]
22 [100, 100]
23 
24 
25 a = [100]
26 def test(num):
27     num=num +num #===>[100]+[100]  ==>num = [100,100] 指向一個新的內存空間
28     print(num) 
29 test(a)
30 print(a)
31 -------------
32 [100,100]
33 [100]
View Code
相關文章
相關標籤/搜索