lambda关键字可以用于创建小巧的匿名函数。
它由参数和一个单独 expression 构成,表达式会在调用时被求值。创建 lambda 函数的句法为 lambda [parameters]: expression。
lambda经常与内置的或functools的某些函数搭配使用:
map(function, iterable, …):
将function函数作用于iterable中的每个元素上,并输出其结果的迭代器。
如果传入了多个iterable参数,那么要求function对应要有相同数量的入参,以对多个iterable同时执行操作。
如果传入的多个可迭代对象长度不同,则最短的可迭代对象遍历结束时,整个迭代停止。
foo = map(lambda x: x ** 2, [1, 3, 5, 7, 9])
print(type(foo)) # <class 'map'>
for _ in foo:
print(_, end=' ') # 1 9 25 49 81
l1 = list(range(1, 6))
l2 = list(range(1, 5)) # 以短的可迭代对象为生成次数
bar = map(lambda x, y: x ** y, l1, l2) # x, y 两个参数对应于l1,l2两个可迭代对象
while True:
try:
print(bar.__next__(), end=' ') # 1 4 27 256
except StopIteration:
break
对于函数的输入已经是参数元组的情况,请参阅 itertools.starmap()。
from itertools import starmap
l1 = list(range(1, 6))
l2 = list(range(1, 5))
baz = starmap(pow, zip(l1, l2)) # 对[(1,1),(2,2),(3,3),(4,4)]逐个执行pow()
for _ in baz:
print(_, end=' ') # 1 4 27 256
filter(function, iterable):
返回iterable中执行function后结果为True的元素,输出结果是一个迭代器。如果function是None,则会假设它是一个身份函数,即以iterable中元素进行Treu/False判断。filter(function, iterable) 相当于一个生成器表达式,当 function 不是 None 的时候为 (item for item in iterable if function(item));function 是 None 的时候为 (item for item in iterable if item) 。
l = [1, 8, 9, 5, 0, 34, 78, 43, 90, 0]
foo = filter(lambda x: x > 40, l)
print(list(foo)) # [78, 43, 90]
bar = filter(None, l)
print(list(bar)) # [1, 8, 9, 5, 34, 78, 43, 90]
如果想让iterable的元素判断为False时才返回,可以使用 itertools.filterfalse() 。
foo = itertools.filterfalse(lambda x: x % 2, l)
print(list(foo))
bar = itertools.filterfalse(None, l) # [8, 0, 34, 78, 90, 0]
print(list(bar)) # [0, 0]
functools.reduce(function, iterable[, initializer]):
将两个参数的 function 从左至右积累地应用到 iterable 的元素,将可迭代对象缩减为单一的值。 例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 是计算 ((((1+2)+3)+4)+5) 的值。
左边的参数 x 是积累值而右边的参数 y 则是来自 iterable 的更新值。 如果存在可选项 initializer,它会被放在参与计算的可迭代对象的条目之前,并在可迭代对象为空时作为默认值。 如果没有给出 initializer 并且 iterable 仅包含一个元素,则将返回第一项。
from functools import reduce
l = [1, 2, 3, 4, 5]
foo = reduce(lambda x, y: x * y, l)
print(foo) # 120 = 1 * 2 * 3 * 4 * 5
bar = reduce(lambda x, y: x * y, l, 0)
print(bar) # 0 = 0 * 1 * 2 * 3 * 4 * 5
baz = reduce(lambda x, y: x * y, [1])
print(baz) # 1
作为排序的key:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
# 或者
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs = sorted(pairs, key=lambda pair: len(pair[1]))
print(pairs) # [(1, 'one'), (2, 'two'), (4, 'four'), (3, 'three')]
builtin内置函数:https://docs.python.org/zh-cn/3/library/functions.html
itertools迭代器函数:https://docs.python.org/zh-cn/3/library/itertools.html
functools高阶函数:https://docs.python.org/zh-cn/3/library/functools.html