---
title: "Python map & reduce 以及lambda匿名函数"
author: "fairy_xzc"
date: "2016-10-13T12:07:09Z"
tags: []
categories: ["编程语言"]
slug: "python-map-reduce-lambda"
draft: false
lastmod: "2016-10-13T15:04:07Z"
id: 2330300
url: "https://agilestyle.iteye.com/blog/2330300"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2330300](/blog/2330300)**

 

## map()

**map()函数接收两个参数，一个是函数，一个是Iterable，map将传入的函数依次作用到序列的每个元素，并把结果作为新的Iterator返回。**

使用map实现一个f(x) = x * x的功能

```
def f(x):
    return x * x


m = map(f, list(range(1, 10)))
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(list(m))
```

另外可以使用lambda函数简化

```
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(list(map(lambda x: x * x, list(range(1, 10)))))
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5888/ae8014ac-4219-3b98-b11e-7697684ab24b.png)

### **Note：**

可以看出 

```
lambda x: x * x
```

实际上就是：

```
def f(x):
    return x * x
```

 

把list中的所有数字转为字符串

```
# ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print(list(map(str, list(range(1, 10)))))
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5890/64a743f1-f523-3118-a531-7cf363f15cd1.png)  
 

## reduce()

**reduce把一个函数作用在一个序列\[x1, x2, x3, ...]上，这个函数必须接收两个参数，reduce把结果继续和序列的下一个元素做累积计算，其效果就是：**

**reduce(f, \[x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)** 

使用reduce对一个序列求和

```
from functools import reduce


def add(x, y):
    return x + y

# 55
print(reduce(add, list(range(1, 11))))
# 55
print(reduce(lambda x, y: x + y, list(range(1, 11))))
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5894/3191731e-8324-35e1-a7eb-bd261d6db622.png)

 

把序列\[1, 2, 3, 4, 5, 6, 7, 8, 9]变换成整数123456789

```
from functools import reduce


def fn(x, y):
    return x * 10 + y


# 123456789
print(reduce(fn, list(range(1, 10))))
# 123456789
print(reduce(lambda x, y: x * 10 + y, list(range(1, 10))))
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5896/514f8211-9872-3dab-8950-d4283ee98998.png)

 

map()和reduce()整合，把str转换位int

```
from functools import reduce


def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]


# '13579' => 13579
print(reduce(fn, map(char2num, '13579')))
# '13579' => 13579
print(reduce(lambda x, y: x * 10 + y, map(char2num, '13579')))


def str2int(s):
    def fn(x, y):
        return x * 10 + y

    def char2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

    return reduce(fn, map(char2num, s))


print(str2int('13579'))
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/5898/d2f12ff5-0bdb-367e-8777-8342591931c4.png)  
 

**参考资料：**

[http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000%20)