一:map():映射

map()有两个参数,一个函数,一个序列,序列中每一个元素都会做为参数传给前边的函数,然后生成新的列表,

第二个参数必须用一个序列:元祖,列表,字符串

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

也可以自己定义函数

搭配lambda函数

>>> map(lambda x:x.upper(),"abc")
['A', 'B', 'C']

map()函数搭配lambda传多个参数

 例子:2个list,[1,2,3][4,5,6],合并为[(1, 4), (2, 5), (3, 6)]

>>> a=[1,2,3]
>>> b=[4,5,6]

>>> map(lambda x,y:(x,y),a,b)
[(1, 4), (2, 5), (3, 6)]

map()传多个参数(序列)时,每次取元素进行map时,是在每个序列的相同位置取值,

然后作为一个元祖传给参数前边的函数的,所以用这个原理,把函数设置None,也可以生成题中的结果,由此也能看到map函数在取值时的逻辑

>>> map(None,list1,list2)

[(1, 4), (2, 5), (3, 6)]

或者用zip()函数也可以
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]

二:lambda匿名函数

lambda语句被用来创建新的函数对象,并且在运行时返回它们。

Python使用lambda关键字来创建匿名函数。这种函数得名于省略了用def声明函数的标准步骤。

lambda只是一个表达式,函数体比def简单很多

lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。

#如下边例子,x,y,z相当于匿名函数中的参数,x+y+z是函数体,匿名函数的定义赋值给了a,a就是一个函数,可以用a()来调用这个函数

>>> a=lambda x,y,z:x+y+z
>>> a(1,2,3)
6

三:filter()

filter和map的区别是,filter保留函数返回为true的值,不返回的不显示

map是保留返回的结果,无论返回的是啥,filter会把不满足true条件的结果忽略掉

例子:删除字符串中的小写字母

#encoding=utf-8
def delete_lowercase(s):
    if s>='a' and s<='z':
        return ""
    else:
        return s

print map(delete_lowercase,"AABBaabb")

print "".join(map(delete_lowercase,"AABBaabb"))

结果:

D:\>python test.py
['A', 'A', 'B', 'B', '', '', '', '']
AABB

保留数字中大于5的位

#-*-coding:utf-8-

def func(n):

if int(n)>5:

return n

print filter(func,"123467")

#只要return的是True,就会保留

结果:

D:\>python test.py
67

或者一行搞定

>>> filter(lambda x:int(x)>=5,"12345678")

'5678'

filter()根据参数中的序列,返回相同形式的序列,列表返回列表,字符串返回字符串

或者一行搞定

>>> filter(lambda x:int(x)>=5,"12345678")

'5678'

>>> filter(lambda x:int(x)>=5,list("12345678"))
['5', '6', '7', '8']

>>> filter(lambda x:int(x)>=5,"12345678")
'5678'

>>> filter(lambda x:int(x)>=5,tuple("12345678"))
('5', '6', '7', '8')

>>> tuple("12345678")
('1', '2', '3', '4', '5', '6', '7', '8')

四:推导列表

>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

相当于把for循环中每次循环得到的数作为一个列表的一个元素,知道所有循环执行结束

各个元素生成的过程相当于以下两句得到的:

for i in range(10):

print i

>>> [i for i in range(10) if i !=5]
[0, 1, 2, 3, 4, 6, 7, 8, 9]

练习:a=[[1,2,3],[4,5,6]]用推导列表生成[[1, 4], [2, 5], [3, 6]]

[[j[i] for j in a] for i in range(3)]

结果:

[[1, 4], [2, 5], [3, 6]]

以上推导列表过程转换成for循环:最外层的for也对应转换成for循环的最外层

>>> for i in range(3):
...     print "\n**************"
...     for j in a:
...         print j[i],
...

结果中有三个元素,每个元素又是包含2个元素的列表,这个元素是执行一次for循环得到的值

拆解过程:

每执行一次完整的循环,生成两个数,这个两个数会以列表的形式作为最后结果列表的一个元素,

也就是说,推导列表的每一步生成的结果会以列表的形式存在,包括最终的结果

>>> for i in range(3):
...     print "\n**************"
...     for j in a:
...         print j[i],
...

**************
1 4
**************
2 5
**************
3 6

五:reduce()累计操作

Reduce()累计操作,要搭配函数来执行

>>> reduce(lambda x,y:x+y,[1,2,3,4])
10

第一次x=1,y=2, x+y=3,之后x+y的结果3赋值给x,y为3

第二次x=3,y=3,x+y=6,之后x+y的结果6赋值给x,y为4

第三次x=3,y=4,x+y=10

>>> 1:1+2  2:3+3  3:6+4

>>> reduce(lambda
x,y:x+y,range(1,101))

5050

>>> reduce(lambda x,y:x+y,[1,2,3])

6

X=1,y=2

结果3传给x

y从第二次开始存结果

reduce(lambda x,y:x+y+y,[1,2,3])

x=1,y=2,y=2
x=5,y=3,y=3

x+y+y=5+3+3=11
x是5就对了

>>> reduce(lambda
x,y:x+x+y,[1,2,3])

x=1,x=1,y=2

x+x+y=1+1+2=4

x=4,x=4,y=3

x+x+y=4+4+3=11

>>> reduce(lambda
x,y:x+x+y,['1','2','3'])

x=1,x=1,y=2

x=’112’,x=’112’,y=’3’

x+x+y='1121123'

六:切片,就是数列的切片,比较基本也比较常用

>>> [1,2,3,4,5][3:5]
[4, 5]

练习:用map,lambda,推到列表,正则,join,去掉字符串中的小写字母

>>> import re
>>> "".join([i for i in map(lambda x:(re.match(r"[A-Z]*",x).group()),"abcABC") if i !=""])
'ABC'

拆解过程:

>>> [i for i in map(lambda x:(re.match(r"[A-Z]*",x).group()),"abcABC") if i !=""]
['A', 'B', 'C']
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i for i in range(10) if i !=5]
[0, 1, 2, 3, 4, 6, 7, 8, 9]
>>> map(lambda x:(re.match(r"[A-Z]*",x).group()),"abcABC")
['', '', '', 'A', 'B', 'C']
>>> lambda x:(re.match(r"[A-Z]*",x).group())("abcABC")
<function <lambda> at 0x00000000054EDB38>
>>> re.match(r"[A-Z]*","ABC").group()
'ABC'

练习:统计字符串中一共有几个数字

s="sdfa45ads46723"

#lambda

>>> filter(lambda x:x.isdigit(),list(s))

['4', '5', '4', '6', '7', '2', '3']

>>> len(filter(lambda x:x.isdigit(),list(s)))

7

>>> reduce(lambda x,y:x+y,map(lambda x:x.isdigit(),list("sdfa45ads46723")))

7

>>> reduce(lambda x,y:x+y,map(lambda x:len(x),filter(lambda x:x.isdigit(),[i for i in s][::-1])))

7

python六剑客:map()、lambda()、filter()、reduce()、推导类表、切片的更多相关文章

  1. python一些内建函数(map,zip,filter,reduce,yield等)

    python一些内建函数(map,zip,filter,reduce,yield等) map函数 Python实际上提供了一个内置的工具,map函数.这个函数的主要功能是对一个序列对象中的每一个元素应 ...

  2. Python中Lambda, filter, reduce and map 的区别

    Lambda, filter, reduce and map Lambda Operator Some like it, others hate it and many are afraid of t ...

  3. Python中的map()函数和reduce()函数的用法

    Python中的map()函数和reduce()函数的用法 这篇文章主要介绍了Python中的map()函数和reduce()函数的用法,代码基于Python2.x版本,需要的朋友可以参考下   Py ...

  4. python 练习用python六剑客实现一个统计数字的个数,六剑客:(map、lambda、reduce、filter、切片、推到列表)

    统计一共有几个数字 s="sdfa45ads46723" #lambda >>> filter(lambda x:x.isdigit(),list(s)) ['4 ...

  5. Python高级特性: 函数编程 lambda, filter,map,reduce

    一.概述 Python是一门多范式的编程语言,它同时支持过程式.面向对象和函数式的编程范式.因此,在Python中提供了很多符合 函数式编程 风格的特性和工具. 以下是对 Python中的函数式编程 ...

  6. Python -- map, Lambda, filter and reduce

    map(func, seq)对seq中的每一个元素,调用func并返回结果.典型的应用是使用lambda函数. >>> def square(x): return x**2 > ...

  7. python Lambda, filter, reduce and map

    1. lambda The lambda operator or lambda function is a way to create small anonymous functions , i.e. ...

  8. python中的map、filter、reduce函数

    三个函数比较类似,都是应用于序列的内置函数.常见的序列包括list.tuple.str.   1.map函数 map函数会根据提供的函数对指定序列做映射. map函数的定义: map(function ...

  9. 简单易懂之python 中的map,filter,reduce用法

    map(function,sequence) 把sequence中的值当参数逐个传给function,返回一个包含函数执行结果的list. 重点是结果返回一个列表,这样对返回的列表就可以干很多的活了. ...

随机推荐

  1. parent.relativePath' points at wrong local POM

    这个错误通常是下载了子项目,没有把父项目下载下来. 子项目要依赖父项目的pom The relative path of the parent pom.xml file within the chec ...

  2. Centos7.2修改时区

    设置时区同样, 在 CentOS 7 中, 引入了一个叫 timedatectl 的设置设置程序. 用法很简单: # timedatectl # 查看系统时间方面的各种状态 Local time: 四 ...

  3. HIT 2739 - The Chinese Postman Problem - [带权有向图上的中国邮路问题][最小费用最大流]

    题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=2739 Time limit : 1 sec Memory limit : 64 M A Chinese ...

  4. gis 相关资料

    --gis原理学习 http://group.cnblogs.com/GIS/best-1.html http://www.cnblogs.com/SuperXJ/tag/移动GIS/ --gis坐标 ...

  5. free详解

    用法: [oracle@server36 ~]$ free -help free: invalid option -- h usage: free [-b|-k|-m|-g] [-l] [-o] [- ...

  6. .Net Identity OAuth 2.0 SecurityStamp 使用

    起源: 近期帮别人做项目,涉及到OAuth认证,服务端主动使token失效,要使对应用户不能再继续访问,只能重新登陆,或者重新授权. 场景: 这种场景OAuth2.0是支持的,比如用户修改了密码,那所 ...

  7. REQUEST FORM 实例

    https://www.programcreek.com/python/example/51524/flask.request.form

  8. 做一个完整的Java Web项目需要掌握的技能[转]

    转自:http://blog.csdn.net/JasonLiuLJX/article/details/51494048 最近自己做了几个Java Web项目,有公司的商业项目,也有个人做着玩的小项目 ...

  9. 2018/04/04 每日一个Linux命令 之 ps

    ps 用于查看系统内的进程状态. 这个命令比较重要,也比较长,会通过实践出常用的命令 -- 当我们敲下一个 ps 之后会发生什么? ubuntu@hong:~/nginx/sites-enabled$ ...

  10. 打造自己的 JavaScript 武器库

    原文 https://segmentfault.com/a/1190000011966867 github:https://github.com/proYang/outils 前言 作为战斗在业务一线 ...