博客
关于我
Python学习(八)——map、reduce、filter、sorted
阅读量:157 次
发布时间:2019-02-27

本文共 1650 字,大约阅读时间需要 5 分钟。

map

map()函数接收两个参数:一个函数,一个序列;map函数将传入函数依次作用于序列的每个元素,把结果作为新的list返回。

将list内的元素转换为数字

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

将list内的数字转换为str

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

求list内元素的绝对值:

>>> map(abs,[-12,-8,2,-9,61,-27])[12, 8, 2, 9, 61, 27]

普通函数实现:

>>> def add(a,b):    return 10*a+b>>> reduce(add,[1,2,3,4,5,6,7,8,9])123456789

reduce

reduce把一个函数f作用在一个序列上,函数f必须接收2个参数;reduce把序列中的抢两个元素传入到函数f中,计算结果接续和下一个元素组合传入函数f中,直到序列的最后一个元素。

>>> def fun(a,b):    return a+b+2>>> reduce(fun,[3,2,1,6,5,4,9,8,7])61
>>> def add(a,b):    return 10*a+b>>> reduce(add,[1,2,3,4,5,6,7,8,9])123456789

filter

filter()函数将传入函数依次作用于序列中的每个元素,返回值为True的元素则保留,False则丢弃,按此规律过滤序列。

滤除3的倍数:

>>> def f(n):    return n%3 !=0>>> filter(f,[1,2,3,4,5,6,7,8,9])[1, 2, 4, 5, 7, 8]

滤除质数:

>>> from math import >>> def notp(n):    if n>1:        for i in range(2,int(sqrt(n))+1):            if(n%i ==0):                return True                 elif n==1:        return True    else:        return False>>> filter(notp,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])[1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20]

sorted

sorted()函数对list进行排序:

>>> sorted([1,2,5,4])[1, 2, 4, 5]>>> sorted([12,45,3,45,78,3,23,4,0,321,235,64,63,1,231,32,1])[0, 1, 1, 3, 3, 4, 12, 23, 32, 45, 45, 63, 64, 78, 231, 235, 321]

sorted对字符串按ASCII大小进行排序:

>>> sorted(['Asc','cmp','w','Xi'])['Asc', 'Xi', 'cmp', 'w']

sorted是高阶函数,可以接收比较函数来自定义实现排序:

>>> def revers(x,y):    if x>y:        return -1    if x
>> sorted([12,45,3,45,78,3,23,4])[3, 3, 4, 12, 23, 45, 45, 78]>>> sorted([12,45,3,45,78,3,23,4],revers)[78, 45, 45, 23, 12, 4, 3, 3]

这里写图片描述

你可能感兴趣的文章
node.js url模块
查看>>
Node.js Web 模块的各种用法和常见场景
查看>>
Node.js 之 log4js 完全讲解
查看>>
Node.js 函数是什么样的?
查看>>
Node.js 函数计算如何突破启动瓶颈,优化启动速度
查看>>
Node.js 切近实战(七) 之Excel在线(文件&文件组)
查看>>
node.js 初体验
查看>>
Node.js 历史
查看>>
Node.js 回调函数的原理、使用方法
查看>>
Node.js 在个推的微服务实践:基于容器的一站式命令行工具链
查看>>
Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
查看>>
Node.js 异步模式浅析
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
Node.js 模块系统的原理、使用方式和一些常见的应用场景
查看>>
Node.js 的事件循环(Event Loop)详解
查看>>
node.js 简易聊天室
查看>>
Node.js 线程你理解的可能是错的
查看>>
Node.js 调用微信公众号 API 添加自定义菜单报错的解决方法
查看>>
node.js 配置首页打开页面
查看>>