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

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

Python 过滤函数 filter 的应用

filter 函数用于对序列中的每个元素应用一个函数,并保留返回值为 True 的元素。以下是 filter 的典型应用示例。

滤除 3 的倍数

from functools import filter
def f(n):
return n % 3 != 0
result = filter(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(result)) # 输出: [1, 2, 4, 5, 7, 8]

滤除质数

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

排序函数 sorted

sorted 函数用于对序列进行排序。默认排序是按升序排序。

对数字排序

sorted([1, 2, 5, 4])  # 输出: [1, 2, 4, 5]

对字符串按 ASCII 排序

sorted(['Asc', 'cmp', 'w', 'Xi'])  # 输出: ['Asc', 'Xi', 'cmp', 'w']

可以接收自定义比较函数

def revers(x, y):
if x > y:
return -1
if x < y:
return 1
return 0
sorted([12, 45, 3, 45, 78, 3, 23, 4], key=revers) # 输出: [78, 45, 45, 23, 12, 4, 3, 3]

转载地址:http://shnd.baihongyu.com/

你可能感兴趣的文章
Netty源码—7.ByteBuf原理四
查看>>
Netty源码—8.编解码原理一
查看>>
Netty源码—8.编解码原理二
查看>>
Netty源码解读
查看>>
Netty的Socket编程详解-搭建服务端与客户端并进行数据传输
查看>>
Netty相关
查看>>
Netty遇到TCP发送缓冲区满了 写半包操作该如何处理
查看>>
Netty:ChannelPipeline和ChannelHandler为什么会鬼混在一起?
查看>>
Netty:原理架构解析
查看>>
Network Dissection:Quantifying Interpretability of Deep Visual Representations(深层视觉表征的量化解释)
查看>>
Network Sniffer and Connection Analyzer
查看>>
Network 灰鸽宝典【目录】
查看>>
NetworkX系列教程(11)-graph和其他数据格式转换
查看>>
Networkx读取军械调查-ITN综合传输网络?/读取GML文件
查看>>
network小学习
查看>>
Netwox网络工具使用详解
查看>>
Net与Flex入门
查看>>
net包之IPConn
查看>>
Net操作配置文件(Web.config|App.config)通用类
查看>>
Neutron系列 : Neutron OVS OpenFlow 流表 和 L2 Population(7)
查看>>