1. fliter
fliter(lambda x:x%3==0,[1,2,3,4,5,6])
# [3,6]
2. map
squares = map(lambda x:x**2,range(5)
print(lsit(squares))
[0,1,4,9,16]
map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
3. sorted
3.1 按照第一个元素排序
a=[('b',3),('a',2),('d',4),('c',1)]
sorted(a,key=lambda x:x[0])
[('a',2),('b',3),('c',1),('d',4)]
3.2 按照第二个元素排序
a=[('b',3),('a',2),('d',4),('c',1)]
sorted(a,key=lambda x:x[1])
[('c',1),('a',2),('b',3),('d',4)]
3.3 指定规则排序
# 获取列表的第二个元素
def takeSecond(elem):
return elem[1]
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# 指定第二个元素排序
random.sort(key=takeSecond)
# 输出类别
print ('排序列表:', random)
4 reduce
from functools import reduce
print(reduce(lambda a,b:'{},{}'.format(a,b),[1,2,3,4,5,6,7,8,9]))
1,2,3,4,5,6,7,8,9
# 从左到右对一个序列的项累计地应用有两个参数的函数,以此合并序列到一个单一值。
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # 计算的就是((((1+2)+3)+4)+5)
5. lambda函数嵌套到普通函数中
def increment(n):
return lambda x:x+n
f=increment(4)
f(2)
6
\
6. 在tkinter中定义内联的callback函数
import sys
from tkinter import Button,mainloop
x=Button(text='Press me',command=(lambda :sys.stdout.write('Hello,World\n')))
x.pack()
x.mainloop()
7. 以XX开头
Names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
B_Name= filter(lambda x: x.startswith('B'),Names)
print(B_Name)
['Bob', 'Barbara']