一、map

Python内置函数,用法及说明如下:

class map(object):
"""
map(func, *iterables) --> map object Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
"""

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

举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下:

def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

map()传入的第一个参数是f,即函数对象本身。由于结果r是一个IteratorIterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。

#使用lambda匿名函数
list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]

  

map()作为高阶函数,事实上它把运算规则抽象了,因此,我们不但可以计算简单的f(x)=x2,还可以计算任意复杂的函数,比如,把这个list所有数字转为字符串:

list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

map函数的优点:

  1. 函数逻辑更加清晰,参数‘f’就表明了对元素的操作
  2. map是高阶函数,可以执行抽象度更高的运算  

二、 reduce

def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
"""
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.
"""
pass

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
reduce(add, [1, 3, 5, 7, 9])
25

匿名函数实现:

reduce(lambda x, y : x + y, [1, 3, 5, 7, 9])
25

当然求和运算可以直接用Python内建函数sum(),没必要动用reduce

但是如果要把序列[1, 3, 5, 7, 9]变换成整数13579reduce就可以派上用场:

from functools import reduce
def fn(x, y):
return x * 10 + y
reduce(fn, [1, 3, 5, 7, 9])
13579

匿名函数实现:

reduce(lambda x, y: x * 10 + y, [1, 3, 5, 7, 9])
13579

这个例子本身没多大用处,但是,如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(),我们就可以写出把str转换为int的函数:

from functools import reduce
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]
reduce(fn, map(char2num, '13579'))
13579

整理成一个str2int的函数就是:

from functools import reduce

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))

还可以用lambda函数进一步简化成:

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

小练习:

  1. 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: 
list(map(lambda x: x.capitalize(), ['adam', 'LISA', 'barT']))
['Adam', 'Lisa', 'Bart']

  2. Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:

def prod(l):
return reduce(lambda x, y: x * y, l)
l = [1, 2 ,3, 4, 5]
print(prod(l))
120

  匿名函数实现:

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

  3. 利用mapreduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:  

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]
def str_split(s):
s1, s2 = s.split('.')
return s1, s2
def str2int_1(s1):
return reduce(lambda x, y: x * 10 + y, map(char2num, s1))
def str2int_2(s2):
return (reduce(lambda x, y: x * 10 + y, map(char2num, s2)))/pow(10, len(s2))
def str2float(s):
s1, s2 = str_split(s)
res = str2int_1(s1) + str2int_2(s2)
return res
a = str2float('123.456')
print(a)
123.456

  

 三、filter

Python内建的filter()函数用于过滤序列。

map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

class filter(object):
"""
filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
"""

例如,在一个list中,删掉偶数,只保留奇数,可以这么写:

def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 3, 5, 7, 9]

同样可以加入匿名函数:

list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 3, 5, 7, 9]

把一个序列中的空字符串删掉,可以这么写:

def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
['A', 'B', 'C']

匿名函数的形式:

list(filter(lambda x: x and x.strip(), ['A', '', 'B', None, 'C', ' ']))
['A', 'B', 'C']

可见用filter()这个高阶函数,关键在于正确实现一个“筛选”函数。

注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。

实例:

用filter求素数

计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单:

首先,列出从2开始的所有自然数,构造一个序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:

3, , 5, , 7, , 9, , 11, , 13, , 15, , 17, , 19, , ...

取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:

5, , 7, , , , 11, , 13, , , , 17, , 19, , ...

取新序列的第一个数5,然后用5把序列的5的倍数筛掉:

7, , , , 11, , 13, , , , 17, , 19, , ...

不断筛下去,就可以得到所有的素数。

用Python来实现这个算法,可以先构造一个从3开始的奇数序列:

def _odd_iter():
n = 1
while True:
n = n + 2
yield n

注意这是一个生成器,并且是一个无限序列。

然后定义一个筛选函数:

def _not_divisible(n):
return lambda x: x % n > 0

最后,定义一个生成器,不断返回下一个素数:

def primes():
yield 2
it = _odd_iter() #初始序列
while True:
n = next(it) #返回序列的第一个数
yield n
it = filter(_n

这个生成器先返回第一个素数2,然后,利用filter()不断产生筛选后的新的序列。

由于primes()也是一个无限序列,所以调用时需要设置一个退出循环的条件:

#打印100以内的素数
for n in primes():
if n < 100:
print(n)
else:
break 2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

注意到Iterator是惰性计算的序列,所以我们可以用Python表示“全体自然数”,“全体素数”这样的序列,而代码非常简洁。

小练习:

  1. 回数是指从左向右读和从右向左读都是一样的数,例如12321909。请利用filter()滤掉非回数:
list(filter(lambda x: str(x) == str(x)[::-1], range(1,1000)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292,
303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626,
636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959,
969, 979, 989, 999]

  思路:先将int数字类型转换为str字符串类型,然后比较原字符串和取反后的字符串是否相等来返回值。

  

  

参考资料:

廖雪峰的官方网站

帮助很大,非常感谢!

  

  

  

  

  

  

  

  

  

  

  

Python基础-map/reduce/filter的更多相关文章

  1. python基础===map, reduce, filter的用法

    filter的用法: 这还是一个操作表list的内嵌函数'filter' 需要一个函数与一个list它用这个函数来决定哪个项应该被放入过滤结果队列中遍历list中的每一个值,输入到这个函数中如果这个函 ...

  2. python基础——map/reduce

    python基础——map/reduce Python内建了map()和reduce()函数. 如果你读过Google的那篇大名鼎鼎的论文“MapReduce: Simplified Data Pro ...

  3. Demo of Python &quot;Map Reduce Filter&quot;

    Here I share with you a demo for python map, reduce and filter functional programming thatowned by m ...

  4. Python: lambda, map, reduce, filter

    在学习python的过程中,lambda的语法时常会使人感到困惑,lambda是什么,为什么要使用lambda,是不是必须使用lambda? 下面就上面的问题进行一下解答. 1.lambda是什么? ...

  5. [python基础知识]python内置函数map/reduce/filter

    python内置函数map/reduce/filter 这三个函数用的顺手了,很cool. filter()函数:filter函数相当于过滤,调用一个bool_func(只返回bool类型数据的方法) ...

  6. python之map、filter、reduce、lambda函数 转

    python之map.filter.reduce.lambda函数  转  http://www.cnblogs.com/kaituorensheng/p/5300340.html 阅读目录 map ...

  7. Python学习:函数式编程(lambda, map() ,reduce() ,filter())

    1. lambda: Python 支持用lambda对简单的功能定义“行内函数” 2.map() : 3.reduce() : 4.filter() : map() ,reduce() , filt ...

  8. python 函数式编程之lambda( ), map( ), reduce( ), filter( )

    lambda( ), map( ), reduce( ), filter( ) 1. lambda( )主要用于“行内函数”: f = lambda x : x + 2 #定义函数f(x)=x+2 g ...

  9. Python map/reduce/filter/sorted函数以及匿名函数

    1. map() 函数的功能: map(f, [x1,x2,x3]) = [f(x1), f(x2), f(x3)] def f(x): return x*x a = map(f, [1, 2, 3, ...

随机推荐

  1. MyEclipse 汉化后切换回英文(中英文切换)

    没事玩玩MyEclipse,按网上的办法把它汉化了!搞了些教程看,教程用的都是英文,还是把MyEclipse也切换回原来的英文得了! 方法:1.复制MyEclipse的快捷方式:2.右键快捷方式-&g ...

  2. DEM反应添加顺序注意问题

    在含有DEM反应的dat中,均相反应的block要在DEM反应之前,例如: @(RXNS) (some reaction equations) @(END) @(DES_RXNS) (some rea ...

  3. 2. Javscript学习笔记——引用类型

    2. 引用类型 2.1 Object类型 Object 是一个基础类型,其他所有类型都从 Object 继承了基本的行为. 对象是一个包含相关数据和方法的集合(通常由一些变量和函数组成,我们称之为对象 ...

  4. Git服务器搭建笔记

    前言:最近公司要使用git服务器对Android4.4的源码进行版本控制,所以花了些时间在Ubuntu14.04上搭建了git服务器,正好前段时间也学习了下git的使用哈哈 ------------- ...

  5. js计算日期相差天数

    日期不能直接相加减比较大小,需要转换一下然后计算最后转换成天,当然,你也可以根据同样类似的方法去转换成小时,或者月,年. function DateDiff(sDate1, sDate2) { //s ...

  6. 原子操作类AtomicInteger详解

    为什么需要AtomicInteger原子操作类?对于Java中的运算操作,例如自增或自减,若没有进行额外的同步操作,在多线程环境下就是线程不安全的.num++解析为num=num+1,明显,这个操作不 ...

  7. Verilog三段式状态机描述

    时序电路的状态是一个状态变量集合,这些状态变量在任意时刻的值都包含了为确定电路的未来行为而必需考虑的所有历史信息. 状态机采用VerilogHDL语言编码,建议分为三个always段完成. 三段式建模 ...

  8. 002-BootStrap基本模板

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...

  9. 九度oj 题目1009:二叉搜索树

    题目1009:二叉搜索树 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:5733 解决:2538 题目描述: 判断两序列是否为同一二叉搜索树序列 输入: 开始一个数n,(1<=n&l ...

  10. 关于发布webservice提示The test form is only available for requests from the local machine

    通过编辑 Web 服务所在的 vroot 的 Web.config 文件,可以启用 HTTP GET 和 HTTP POST.以下配置同时启用了 HTTP GET 和 HTTP POST: <c ...