Lambda表达式是一种匿名函数,可以在需要函数对象的地方使用。它最常见的用途是作为高阶函数的参数,例如在'map'、'filter'、'reduce'等函数中使用。

以下是一些Lambda表达式的示例代码:

  1. 在'map'函数中使用Lambda表达式,将列表中每个元素加上1:
numbers = [1, 2, 3, 4, 5]
result = map(lambda x: x + 1, numbers)
print(list(result))  # [2, 3, 4, 5, 6]
  1. 在'filter'函数中使用Lambda表达式,筛选出列表中所有的偶数:
numbers = [1, 2, 3, 4, 5]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))  # [2, 4]
  1. 在'reduce'函数中使用Lambda表达式,求列表中所有元素的和:
from functools import reduce

numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result)  # 15
  1. 在'sorted'函数中使用Lambda表达式,按照元素长度排序:
fruits = ['apple', 'banana', 'orange', 'kiwi']
result = sorted(fruits, key=lambda x: len(x))
print(result)  # ['kiwi', 'apple', 'banana', 'orange']
  1. 在函数中使用Lambda表达式,返回一个加法函数:
def make_adder(n):
    return lambda x: x + n

add5 = make_adder(5)
print(add5(10))  # 15
Lambda表达式详解:使用场景及示例代码

原文地址: https://www.cveoy.top/t/topic/ozV7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录