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

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

Python 过滤函数 filter 的应用

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

滤除 3 的倍数

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

滤除质数

from math import sqrtfrom functools import filterdef notp(n):    if n > 1:        for i in range(2, int(sqrt(n)) + 1):            if n % i == 0:                return True    return Falseresult = 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 0sorted([12, 45, 3, 45, 78, 3, 23, 4], key=revers)  # 输出: [78, 45, 45, 23, 12, 4, 3, 3]

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

你可能感兴趣的文章
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>