文章预览
1.简单的算术运算: add = lambda x, y: x + y subtract = lambda x, y: x - y multiply = lambda x, y: x * y divide = lambda x, y: x / y print (add(3, 5)) print (subtract(8, 3)) print (multiply(4, 6)) print (divide(10, 2)) 8 5 24 5.0 2.对元组列表进行排序: pairs = [(1, 5), (2, 3), (4, 1), (3, 8)] sorted_pairs = sorted(pairs, key=lambda x: x[1]) print (sorted_pairs) [(4, 1), (2, 3), (1, 5), (3, 8)] 3. 过滤列表: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print (even_numbers) [2, 4, 6, 8] 4.将函数映射到列表: numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x**2, numbers)) print (squared_numbers) [1, 4, 9, 16, 25] 5.使用 Lambda、 map 和 filter: # 使用 map 将列表中的每个元素加倍 numbers = [ 1 , 2 , 3 , 4 , 5 ] doubled_numbers = list(map( lambda
………………………………