匿名函数 lambda
格式:
lambda 参数1,参数2,... : 运算
常见的使用场景
- 结合内置函数使用
函数定义 | 解释 |
---|---|
max(iterable, *[, default=obj, key=func]) -> value | 取最大值 |
min(iterable, *[, default=obj, key=func]) -> value | 取最小值 |
sorted(iterable, /, *, key=None, reverse=False) | 排序 |
map(func, *iterables) --> map object | map() 会根据提供的函数对指定序列中的每一个元素做映射。 |
reduce(function, sequence[, initial]) -> value | reduce() 函数会对参数序列中元素进行累积。 |
filter(function or None, iterable) --> filter object | filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。 |
示例
- 结合max 、min函数使用
# 结合max 、min函数使用
demo_list = [{'a':10,'b':20},{'a':15,'b':20}]
print(max(demo_list,key=lambda x:x['a']))
print(min(demo_list,key=lambda x:x['a']))
输出结果:
{'a': 15, 'b': 20}
{'a': 10, 'b': 20}
- 结合sorted使用
sorted(demo_list,key=lambda x:x['a'],reverse=False)
输出结果:
[{'a': 10, 'b': 20}, {'a': 15, 'b': 20}]
- 结合map()使用
# 结合map使用
# 对于每个元素进行 + 1 操作
demo_list = [1,2,3,4,5,6]
# 返回map对象,强制转换
list(map(lambda x:x+1,demo_list))
输出结果:
[2, 3, 4, 5, 6, 7]
- 结合reduce()使用
在Python 3里,reduce()
函数已经被从全局名字空间里移除了,它现在被放置在fucntools
模块里
使用前需要先引用
from functools import reduce
示例
from functools import reduce
# 结合reduce使用
demo_list = [1,2,3,4,5,6]
reduce(lambda x,y:x+y,[1,2,3,4,5,6])
输出结果:
21
- 结合filter()使用
# 结合filter使用
demo_list = [-1,-2,-3,4,5,6]
list(filter(lambda x:x>0,demo_list))
输出结果:
[4, 5, 6]