匿名函数
- 匿名函数在创建时不需要命名,所以叫匿名函数。
- 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果
def add(a, b):
return a+b
print(add(1, 3))
add2 = lambda x, y: x + y
print(add2(1, 3))
4
4
Process finished with exit code 0
add2 = lambda *x: sum(x)
print(add2(1, 3, 6, 5))
15
Process finished with exit code 0
常见使用场景
comp = lambda x, y: x if x>y else y
print(f"最大值:{comp(2, 3)}")
最大值:3
Process finished with exit code 0
f = lambda x: float('%2f'%x)
print(f(3.466544))
3.47
Process finished with exit code 0
# sorted => 内建函数 => 排序
# sorted(要排序的对象, key=函数)
mylist = [-1, 10, 8, -9, 6, 3]
print(sorted(mylist))
[-9, -1, 3, 6, 8, 10]
Process finished with exit code 0
print(sorted(mylist, key=lambda x: x if x>0 else -x))
mystr = "AsdBcmG"
print(sorted(mystr, key=lambda x: x.lower()))