一、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. 2017 Multi-University Training Contest - Team 4 hdu6069 Counting Divisors

    地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=6069 题目: Counting Divisors Time Limit: 10000/5000 ...

  2. 杭电1019Least Common Multiple

    地址:http://acm.hdu.edu.cn/showproblem.php?pid=1019 题目: Problem Description The least common multiple ...

  3. POJ - 2175 Evacuation Plan (最小费用流消圈)

    题意:有N栋楼,每栋楼有\(val_i\)个人要避难,现在有M个避难所,每个避难所的容量为\(cap_i\),每个人从楼i到避难所j的话费是两者的曼哈顿距离.现在给出解决方案,问这个解决方案是否是花费 ...

  4. NC学习笔记

    NC基础技术  一.NC开发基本概念        1.单据:一般是由表头,表体,表位组成.                   表头:一般是一些主信息,例如日期,项目等               ...

  5. 设置eclipse编码格式

    1.修改eclipse默认工作空间编码方式.点击Window-->Preferences-->General-->Workspace,设置编码格式为UTF-8,然后点击OK.

  6. Eclipse+Spark搭建源码分析环境问题分析

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...

  7. 手写Bind

    Function.prototype.bind2 = function(context){ var self = this; var args = [].slice.call(arguments,1) ...

  8. linux系统中python版本升级

    一,查看python版本号 python -V 二,下载需要升级到python版本包下载地址https://www.python.org/ftp/python/ 根据需要选择需要的python版本 e ...

  9. 【Python】高阶函数

    filter def is_palindrome(n): L = str(n) i = 0 j = len(L) - 1 while i != j: if L[i] != L[j]: return F ...

  10. CentOS修改时区、日期、时间

    一.时区 显示时区 date --help 获取帮助 date -R date +%z 修改时区 cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime ...