python lambda 形参列表 : 因变量归来值表白式语句

python lambda 形参列表 : 因变量归来值表白式语句

Lambda表白式是Python中一类特出的设置因变量的情势,运用它不妨设置一个隐姓埋名因变量。与其它谈话各别,Python的Lambda表白式的因变量体只能有独立的一条语句,也即是归来值表白式语句。其语法如次:

lambda 形参列表 : 因变量归来值表白式语句

底下是个Lambda表白式的例子:

#!/usr/bin/envpython

li=[{"age":20,"name":"def"},{"age":25,"name":"abc"},{"age":10,"name":"ghi"}]

li=sorted(li, key=lambda x:x["age"])

print(li)

即使不必Lambda表白式,而要写成惯例的因变量,那么须要这么写:

#!/usr/bin/envpython

def comp(x):

    return x["age"]

li=[{"age":20,"name":"def"},{"age":25,"name":"abc"},{"age":10,"name":"ghi"}]

li=sorted(li, key=comp)

print(li)

分享到 :

Leave a Reply

Your email address will not be published. Required fields are marked *