lambda表达式 匿名函数

时间:2023-03-08 17:17:57

lambda函数是一种快速定义单行最小函数的方法,是从Lisp借鉴而来的,可以用在任何需要函数的地方。

基础

lambda语句中,冒号前是参数,可以有多个,用逗号分割;冒号右边是返回值。 
lambda语句构建的是一个函数对象。

# 两个参数,x和y,返回两个参数的和
>>> f = lambda x, y: x+y
>>> type(f)
<type 'function'>
>>> f
<function <lambda> at 0x7f6d023000c8>
>>> f(10, 12)
22
>>> f("hello ", "world")
'hello world'

map

map(…) 函数官方文档 
map函数结果生成一个list,参数为函数、一个或多个序列;如果函数的参数只有一个,那么应该有一个序列,有多个参数,那么应该有相应数量的序列。 
简单的说:map(function,sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回 
map(function, sequence[, sequence, …]) -> list

Return a list of the results of applying the function to the items of the argument sequence(s).  If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length.  If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).
  • 1
  • 2

>>> map(lambda x: x*2, range(1,10))
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> map(lambda x, y: x*y, range(1,10), range(2, 11))
[2, 6, 12, 20, 30, 42, 56, 72, 90]
>>> map(lambda x: 1, range(1,10))
[1, 1, 1, 1, 1, 1, 1, 1, 1]

官方文档中最后一句解释,特别重要: map函数的参数中有一个是function(函数),这个函数也可以是None(那句话的意思不是返回值是None)。如果是None的话,map就与zip函数类似了,看下面的例子, 区别已经在zip函数介绍过了。

>>> map(None, range(10), range(1, 11))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
>>> zip(range(10), range(1, 11))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
>>> zip(range(10))
[(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]
>>> map(None, range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

因此,map函数的执行过程,……不好描述啊……

reduce

reduce(function,sequence):对sequence中的item顺序迭代调用function。 
reduce(…) 官方文档 
reduce(function, sequence[, initial]) -> value 
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. 
根据文档里面显示的代码:

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
15
# 内部执行过程,((((1+2)+3)+4)+5) # list只有一个元素
>>> reduce(lambda x: x+2, [1])
1 #reduce 如果list的长度大于1,lambda表达式必须有两个参数(大于2个参数是不对的)
>>> reduce(lambda x: x+2, [1, 2, 3, 4, 5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)

filter

filter(function,sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回。

>>> filter(lambda x:x>10, range(1,20))
[11, 12, 13, 14, 15, 16, 17, 18, 19] >>> filter(lambda s: s != 'a' , 'abcdefg')
'bcdefg'