Python——map()

简介

本篇笔记简单记录Python内建函数map()reduce()函数几种使用示例。

map()

函数接收两个参数,一是函数,一是待处理的序列,map将传入的函数一次作用到序列的每一个元素,并把结果作为新的list返回。如:

e.g. 1

1
2
3
4
5
6
def add10(x):
return x+10
temp = [2,4,8,9,1]
map(add10,temp)
print(temp)
#[12,14,18,19,11]

e.g. 2

1
2
>>> map(str,[1,2,3,4])
['1','2','3','4']

e.g. 3

1
2
3
4
5
6
7
def abc(a, b, c):
return a*10000 + b*100 + c
list1 = [11,22,33]
list2 = [44,55,66]
list3 = [77,88,99]
map(abc,list1,list2,list3)
#[114477, 225588, 336699]

如果函数参数为None,自动假定一个identity函数,如:

1
2
3
4
5
6
7
8
list1 = [11,22,33]
map(None,list1)
#[11, 22, 33]
list1 = [11,22,33]
list2 = [44,55,66]
list3 = [77,88,99]
map(None,list1,list2,list3)
#[(11, 44, 77), (22, 55, 88), (33, 66, 99)]

reduce()

reduce把一个函数f作用在一个序列上,函数f必须接受两个参数,reduce把结果继续和序列下一个元素做累积计算,功效等价于:

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

e.g. 1

1
2
3
4
5
6
from functools import reduce
def add(x, y):
return x*10 + y
reduce(add, [1, 3, 5, 7, 9])
#13579

map reduce实现str2int

1
2
3
4
5
6
7
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
temp={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return temp[s]
return reduce(fn, map(char2num, s))

进一步使用lambda函数简化成:

1
2
3
4
5
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]
def str2int(s):
return reduce(lambda x,y: x*10+y, map(char2num, s))

分享