1. 程式人生 > >python基礎之lambda表示式

python基礎之lambda表示式

一. 在排序中的應用

例:

>>> List=[{"name":"wan gang","age":22,"gender":"boy","score":583},
	{"name":"zhang mei","age":21,"gender":"girl","score":530},
	{"name":"li niu","age":22,"gender":"boy","score":581},
	{"name":"he meimei","age":23,"gender":"girl","score":509},
	{"name":"ma yun","age":26,"gender":"boy","score":492},
	{"name":"niu fang","age":25,"gender":"girl","score":614},
	{"name":"zhao yun","age":20,"gender":"boy","score":505}]
>>> List.sort(key=lambda x:x["score"]) #按照score進行排序
>>> List
    [{'name': 'ma yun', 'age': 26, 'gender': 'boy', 'score': 492}, 
    {'name': 'zhao yun', 'age': 20, 'gender': 'boy', 'score': 505}, 
    {'name': 'he meimei', 'age': 23, 'gender': 'girl', 'score': 509}, 
    {'name': 'zhang mei', 'age': 21, 'gender': 'girl', 'score': 530}, 
    {'name': 'li niu', 'age': 22, 'gender': 'boy', 'score': 581}, 
    {'name': 'wan gang', 'age': 22, 'gender': 'boy', 'score': 583}, 
    {'name': 'niu fang', 'age': 25, 'gender': 'girl', 'score': 614}]

二.作為實參傳入函式,可以改變函式的功能

例:

>>> def test(a,b,func):
	sum=func(a,b)
	return sum

>>> a=3
>>> b=5
>>> test(a,b,lambda x,y:x+y)  #此時,整個lambda表示式作為實參,x,y依舊時lambda中的形參
8
>>> test(a,b,lambda x,y:x*y)  #lambda表示式不同,呼叫test得到的值不同
15
>>> test(a,b,lambda x,y:x*y+100)
115

關鍵字 eval 可以將字串“lambda x,y:x+y"變為lambda表示式。

例:

>>> def test(a,b,func):
	sum=func(a,b)
	return sum
>>> a=3
>>> b=5
>>> func=input("輸入lambda表示式:")
輸入lambda表示式:lambda x,y:x-y
>>> func_new=eval(func)  #用eval將上面輸入的字串"lambda x,y:x-y"轉換為lambda表示式
>>> test(a,b,func_new)
-2