码迷,mamicode.com
首页 > 编程语言 > 详细

python 高阶函数 map()和reduce()

时间:2017-12-16 22:09:20      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:str   tools   style   lambda   code   span   一个   post   port   

一、map()函数

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

 1 >>> from collections import Iterator
 2 >>> def f(x):
 3 ...     return x * x
 4 ... 
 5 >>> r = map(f, [1, 2, 3, 4, 5])
 6 >>> r
 7 <map object at 0x1013e5748>
 8 >>> isinstance(r, Iterator)
 9 True
10 >>> list(r)
11 [1, 4, 9, 16, 25]

二、reduce()函数

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

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
1 >>> from functools import reduce
2 >>> def ad(x, y):
3 ...     return x + y
4 ... 
5 >>> reduce(ad, [1, 3, 5, 7, 9])
6 25
 1 >>> from functools import reduce
 2 >>> DIGITS = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
 3 >>> def char2num(s):
 4 ...     return DIGITS[s]
 5 ... 
 6 >>> def str2int(s):
 7 ...     return reduce(lambda x, y: x * 10 + y, map(char2num, s))
 8 ... 
 9 >>> str2int(123456)
10 123456

 

python 高阶函数 map()和reduce()

标签:str   tools   style   lambda   code   span   一个   post   port   

原文地址:http://www.cnblogs.com/gundan/p/8047728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!