一、map、filter、reduce

  map(fuction , iterable)   映射  对可迭代对象中的每一项,使用函数去改变

  filter(function, iterable)  过滤  可迭代对象中的每一项,放到函数中去计算,如何为真,则留下,构造成一个迭代器,为假则去除

  reduce(fuction,iterable)  减少  把元素中的左边的合并到右边去。

1.1 map  映射

  官方定义:Return an iterator that applies function to every item of iterable, yielding the results.

        返回一个迭代器,它对每个迭代项应用函数,得到结果。

  why:不使用for循环,就能将序列中的数据m--映射到给定的处理函数中。快速的对一个序列进行各种操作

numbers = [1, 3, 5, 7, 9]

# 改写成2,4,6,8,10

#普通做法
new_num = []
for x in numbers:
new_num.append(x+1) print(new_num) # map版本
def addone(x):
return x+1 print(list(map(addone, numbers))) # 其他应用 改写字符串
str_list = ['lilei', 'hmm', 'de8ug']
def change(s: str):
return s.upper() print(list(map(change, str_list)))

1.2 filter 过滤、筛选

  官方: Construct an iterator from those elements of iterable for which function returns true.

      iterable may be either a sequence, a container which supports iteration, or an iterator.

      If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

      从可迭代的元素中构造一个迭代器,函数返回true。iterable可以是一个序列,一个支持迭代的容器,

      或者一个迭代器。如果函数为None,则假定标识函数为false,即为 false的所有元素都被删除。

  why:不用for循环, 就能将序列中的数据一一映射到给定 的处理函数, 函数中添加了真假判断,

     True则返回 相应数据,最终得到筛选后的序列。

'''
查找大于30 小于50的数字列表
'''
my_list = [24,23,75,12,43,9,42,28,37]
# 普通版本
new_list = [] for i in my_list:
if 30 < i < 50:
new_list.append(i)
print(new_list) # filter版本
def choose(x):
# if 30 < i < 50:
# return True
return 30 < x < 50 # < 操作的结果,已经是bool 类型了 print(list(filter(choose, my_list))) # 字符串操作
import re
str_list = ['lilei', 'hmm', 'de8ug', 'debug1', 'de8ug2'] def lh(s: str):
return re.search('de8ug', s) print(list(filter(lh, str_list)))

1.3 reduce 减少,合并

  官方:Apply function of two arguments cumulatively to the items of sequence, from left to right,

     so as to reduce the sequence to a single value.

     将两个参数的函数累积到序列的项上,从左到右,以便将序列减少到单个值。

  why: 为了快速的进行累加,连乘的计算 使代码更简洁

  需要注意:py3中吧reduce放到了fuctiontools这个模块下了

from functools import reduce

numbers = [1, 3, 5, 7, 9]

# 普通版本 累加
count = 0
for i in numbers:
count += i
print(count) # reduce版 累加
def add(x, y):
return x+y print(reduce(add, numbers)) # 普通版本 连乘
count = 1
for i in numbers:
count *= i
print(count) # reduce版本 连乘
def mul(x, y):
return x*y
print(reduce(mul, numbers))

二、 lambda表达式

2.1  基本知识概览

2.2 代码部分"1. 单参数 和 判断"

f = lambda x: x*2
f(2) # f = lambda x: True if x>8 else False
print(f(9)) # True "2. 多参数"
x = lambda x,y: x*y+2
print(x(2,3)) # "3. 排序"
users = [('de8ug', 18, 1), ('lilei', 20, 2), ('hmm', 17, 3), ('zhangsan', 30, 4)]
users.sort(key=lambda x: x[1]) # x代表字典,每一个数组,要对谁排序,直接加上该位置
users.sort(key=lambda x:(x[1],x[2])) . # 双排序
print(users) "4. 字典的默认值"
from collections import defaultdict # 生成默认的数值
d = defaultdict(lambda :0)
d[1]
print(d) # defaultdict(<function <lambda> at 0x101ab9950>, {1: 0}) # 生成默认的字符串
d = defaultdict(lambda :'abc')
d[1]
print(d) # defaultdict(<function <lambda> at 0x101ab9950>, {1: 'abc'}) # 生成二元数组,给地理信息使用
point = defaultdict(lambda :(2,3))
point['p1']
print(point) # defaultdict(<function <lambda> at 0x105a89950>, {'p1': (2, 3)}) "5. 在map,reduce,filter中使用,可以减少函数的定义"
# 代码省略,看上面部分的代码

  

map、filter、reduce、lambda的更多相关文章

  1. ES6 数组遍历方法的实战用法总结(forEach,every,some,map,filter,reduce,reduceRight,indexOf,lastIndexOf)

    目录 forEach every some map filter reduce && reduceRight indexOf lastIndexOf 前言 ES6原生语法中提供了非常多 ...

  2. python的map,filter,reduce学习

    python2,python3中map,filter,reduce区别: 1,在python2 中,map,filter,reduce函数是直接输出结果. 2,在python3中做了些修改,输出前需要 ...

  3. Python 函数之lambda、map、filter和reduce

    1.lambda函数 lambda()是Python里的匿名函数,其语法如下: lambda [arg1[, arg2, ... argN]]: expression 学习条件运算时,对于简单的 if ...

  4. python迭代和解析(3):range、map、zip、filter和reduce函数

    解析.迭代和生成系列文章:https://www.cnblogs.com/f-ck-need-u/p/9832640.html range range()是一个内置函数,它返回一个数字序列,功能和Li ...

  5. python高阶函数,map,filter,reduce,ord,以及lambda表达式

    为什么我突然扯出这么几个函数,是因为我今天在看流畅的python这本书的时候,里面有一部分内容看的有点懵逼. >>> symbols = '$¢£¥€¤' >>> ...

  6. 内置函数--map,filter,reduce

    一.map class map(object): """ map(func, *iterables) --> map object Make an iterator ...

  7. python的 map,filter, reduce, enumerate

    一, map     #基本的map运用都可以用解析去替代,复杂的仍然需要定义函数,利用map去做 map(函数, 序列) 将序列的各项经过函数处理, 然后返回到一个新列表中. #itertools. ...

  8. Map、Filter和Reduce函数(Python)

    Map map(function_to_apply, list_of_inputs) 设有以下代码: >>> items = [1, 2, 3, 4, 5] >>> ...

  9. 160909、Filter多方式拦截、禁用IE图片缓存、Filter设置字符编码

    dispatcher多方式拦截 我们来看一个例子 我们定义一个index.jsp,里面有一个链接跳转到dispatcher.jsp页面 <body> <a href="di ...

  10. Servlet生命周期 、Filter生命周期、Listering(监听器)总结

    Servlet生命周期简述 (1)加载和实例化 当Servlet容器启动或客户端发送一个请求时,Servlet容器会查找内存中是否存在该Servlet实例,若存在,则直接读取该实例响应请求:如果不存在 ...

随机推荐

  1. Mac OS OpenVpN 连接设置(转)

    下文介绍Mac OS连接使用OpenVPN方法教程,使用的软件是免费开源的Tunnelblick,当然也有其它连接软件,比如Viscosity,不过这个是付费的,还是前面的用的多. 1.下载安装Tun ...

  2. 写几个简单用artTemplate的例子

    写几个简单的artTemplate的例子,很多框架都有自己的模板(template),没得时候,可以利用artTemplate.js完成 html文件是: <!DOCTYPE html> ...

  3. 【1】Kali Linux的安装及配置

    爱生活就得够GEEK. ---------------------------------------------------------------完美的分割线------------------- ...

  4. SparkStreaming程序设计

    一个简单的 Streamin wordCount object StreamingWordCount { def main(args: Array[String]): Unit = { val spa ...

  5. Axure的总结

    1.Axure的用途      Axure RP 能帮助网站需求设计者,快捷而简便的创建基于网站构架图的带注释页面示意图.操作流程图.以及交互设计,并可自动生成用于演示的网页文件和规格文件,以提供演示 ...

  6. git服务器-------》用户免密git操作

    找到/etc/ssh/sshd_config文件 开启 RSAAuthentication yesPubkeyAuthentication yesAuthorizedKeysFile      .ss ...

  7. BZOJ3150: [Ctsc2013]猴子

    传送门 这题好神啊..好神啊.. 首先得到简单的DP方程: $f_{\{ i \}}=\frac{\sum_{i \ne j} f_ {\{ i,j \}} \times P_{(i,j)}}{N-1 ...

  8. 教你如何挑选深度学习GPU【转】

    本文转载自:https://blog.csdn.net/qq_38906523/article/details/78730158 即将进入 2018 年,随着硬件的更新换代,越来越多的机器学习从业者又 ...

  9. Oracle SQL Developer 编辑区不能删除,后退,空格,复制粘贴等功能都失效的解决办法

    Oracle SQL Developer 编辑区不能删除,后退,空格,复制粘贴等功能都失效的解决办法 解决: 打开菜单并选择Tools-prefrence-Accelerators-Load Pres ...

  10. 分分钟解决 MySQL 查询速度慢与性能差

    一.什么影响了数据库查询速度 1.1 影响数据库查询速度的四个因素 1.2 风险分析 QPS: QueriesPerSecond意思是“每秒查询率”,是一台服务器每秒能够相应的查询次数,是对一个特定的 ...