# 最简单的理解lambda，map，reduce，filter，列表推导式

Python 2.7
IDE Pycharm 5.0.3

## 为什么要用Lambda

``````#定义一个函数
def Whatever(x,y):
return x*y+x

#调用函数
f = Whatever(22,3)
print f
#88
``````

``````print (lambda x,y:x*y+x)(x=22,y=3)
``````

``````f = lambda x,y:x*y+x
print f(22,3)
``````

## 为什么要用map

``````print (lambda x,y:x*y+x)(x=22,y=3)
``````

``````print map(lambda x,y:x*y+x,[22],[3])
#[88]
``````

``````print map(lambda y,x:x*y+x,[22],[3])
#[69]
``````

``````print map(lambda x,y:x*y+x,[22,3," ","MrLevo"],[3,22,3,2])
#[88, 69, '    ', 'MrLevoMrLevoMrLevo']
``````

``````def Whatever(x,y):
return x*y+x
``````

``````print map(Whatever,[22,3," ","MrLevo"],[3,22,3,2])
#[88, 69, '    ', 'MrLevoMrLevoMrLevo']
``````

``````print map(None,[22,3," ","MrLevo"],[3,22,3,2])
#[(22, 3), (3, 22), (' ', 3), ('MrLevo', 2)]
``````

## 为什么要用reduce

• 方法一：for循环
``````def Factorial(n):
result=1
for i in range(1,n+1):
result = result*i
return result

result = Factorial(5)
print result
#120
``````
• 方法二，递归法
``````def Factorial(n):
if n==1 or n==0:
return 1
return n*Factorial(n-1)

result = Factorial(5)
print result
#120
``````

``````print reduce(lambda x,y:x*y,[1,2,3,4,5])
#120
``````

• 步骤一：x=1,y=2
• 步骤二：x = xy = 12=2
• 步骤三：x=2 , 取出y=3
• 步骤四：x=2*3=6
• 步骤五：x=6 ，取出y=4
• 步骤六：x = x*y = 24
• 步骤七：x=24，取出y=5
• 步骤八：x = 24*5=120
• 结束

map表示不服，说道要是阶乘是250！呢，怎么办，不会要这么写到[1,2,3,,,,,,,250]把，于是reduce叫来了列表推导式。。。

``````print reduce(lambda x,y:x*y,[x for x in range(1,6)])
#120
``````

``````print [i for i in range(1,6)]
#[1, 2, 3, 4, 5]
``````

``````result = []
for i in range(1,6):
result.append(i)
print result
##[1, 2, 3, 4, 5]
``````

## Filter表示不服

``````print [x for x in range(1,6) if x%2==1]
#[1, 3, 5]
``````

filter，map，reduce一脸懵逼。。。。。
filter：不行，这个规则太简单，我们，我们，我们来筛选非空白字符`['MrLevo', '', '520', None, ' ']`把它筛选成`['MrLevo', '520']`哼！

filter，map，reduce一脸懵逼。。。。。

filter：我，你，我，额。。。

``````def NoEmpty(x):
if x and x.strip():
return x

print filter(NoEmpty,['MrLevo', '', '520', None, ' '])
``````

filter(function, sequence)，作用是按照所定义的函数过滤掉列表中的一些元素。删选规则复杂一点，需要用函数定义那种复杂，可以用filter，不然还是列表推导式把，就是对其他程序员可能不太友好如果列表推导式太长的话。

## 致谢

@Alex--Python一些特殊用法(map、reduce、filter、lambda、列表推导式等)