lambda表达式使用场景及示例代码
Lambda表达式是一种匿名函数,可以在需要函数对象的地方使用。它最常见的用途是作为高阶函数的参数,例如在map、filter、reduce等函数中使用。
以下是一些Lambda表达式的示例代码:
- 在map函数中使用Lambda表达式,将列表中每个元素加上1:
numbers = [1, 2, 3, 4, 5]
result = map(lambda x: x + 1, numbers)
print(list(result)) # [2, 3, 4, 5, 6]
- 在filter函数中使用Lambda表达式,筛选出列表中所有的偶数:
numbers = [1, 2, 3, 4, 5]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result)) # [2, 4]
- 在reduce函数中使用Lambda表达式,求列表中所有元素的和:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result) # 15
- 在sorted函数中使用Lambda表达式,按照元素长度排序:
fruits = ['apple', 'banana', 'orange', 'kiwi']
result = sorted(fruits, key=lambda x: len(x))
print(result) # ['kiwi', 'apple', 'banana', 'orange']
- 在函数中使用Lambda表达式,返回一个加法函数:
def make_adder(n):
return lambda x: x + n
add5 = make_adder(5)
print(add5(10)) # 15
``
原文地址: http://www.cveoy.top/t/topic/g1zm 著作权归作者所有。请勿转载和采集!