Python 函数之lambda、map、filter和reduce
1、lambda函数
lambda()是Python里的匿名函数,其语法如下:
lambda [arg1[, arg2, ... argN]]: expression
学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:
# 普通条件语句
if 1 == 1:
name = 'evescn'
else:
name = 'gm' # 三元运算
name = 'evescn' if 1 == 1 else 'gm'
对于简单的函数,也存在一种简便的表示方式,即:lambda表达式
# ###################### 普通函数 ######################
# 定义函数(普通方式)
def func(arg):
return arg + 1 # 执行函数
result = func(123) # ###################### lambda ###################### # 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1 # 执行函数
result = my_lambda(123)
lambda存在意义就是对简单函数的简洁表示,下面在举一个列表的例子
l = [11, 22, 33, 44] new_l = map(lambda x: x + 10, l) a = list(new_l)
print(a) # 输出结果
[21, 32, 43, 54]
2、map函数
map(function, sequence[, sequence, ...])
map 函数会对序列参数 sequence 中的每个元素调用 function 函数,返回的结果为每一个元素调用function函数的返回值
l = [11, 22, 33, 44] def myadd(x):
return x + 10 new_n = map(myadd, l) b = list(new_n)
print(b) # 输出结果
[21, 32, 43, 54]
利用map()
函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT']
,输出:['Adam', 'Lisa', 'Bart']
:
# -*- coding: utf- -*- def normalize(str):
return str.capitalize() # 测试:
L1 = ['adam', 'LISA', 'barT', 'ROOT']
L2 = list(map(normalize, L1))
print(L2) # 输出结果
['Adam', 'Lisa', 'Bart', 'Root']
3、filter 函数
对于序列中的元素进行筛选,最终获取符合条件的序列
def myfunc(x):
if x > 30:
return True
else:
return False a = [11, 22, 33] new_a = filter(myfunc,a) b = list(new_a)
print(b) # 输出结果
[33]
4、reduce函数
对于序列内所有元素进行累计操作
reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
比方说对一个序列求和,就可以用reduce
实现:
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
当然求和运算可以直接用Python内建函数sum()
,没必要动用reduce
。
但是如果要把序列[1, 3, 5, 7, 9]
变换成整数13579
,reduce
就可以派上用场:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
这个例子本身没多大用处,但是,如果考虑到字符串str
也是一个序列,对上面的例子稍加改动,配合map()
,我们就可以写出把str
转换为int
的函数:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> def char2num(s):
... return {'': 0, '': 1, '': 2, '': 3, '': 4, '': 5, '': 6, '': 7, '': 8, '': 9}[s]
...
>>> reduce(fn, map(char2num, ''))
13579
整理成一个str2int
的函数就是:
from functools import reduce def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'': 0, '': 1, '': 2, '': 3, '': 4, '': 5, '': 6, '': 7, '': 8, '': 9}[s]
return reduce(fn, map(char2num, s))
还可以用lambda函数进一步简化成:
from functools import reduce def char2num(s):
return {'': 0, '': 1, '': 2, '': 3, '': 4, '': 5, '': 6, '': 7, '': 8, '': 9}[s] def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
也就是说,假设Python没有提供int()
函数,你完全可以自己写一个把字符串转化为整数的函数,而且只需要几行代码!
http://www.cnblogs.com/wupeiqi/articles/4943406.html
Python 函数之lambda、map、filter和reduce的更多相关文章
- python几个重要的函数(lambda,filter,reduce,map,zip)
一.匿名函数lambda lambda argument1,argument2,...argumentN :expression using arguments 1.lambda是一个表达式,而不是一 ...
- Python面试题之Python中的lambda map filter reduce zip
当年龟叔想把上面列出来的这些都干掉.在 “All Things Pythonic: The fate of reduce() in Python 3000”这篇文章中,他给出了自己要移除lambda. ...
- [Python学习笔记-002] lambda, map, filter and reduce
1. lambda lambda, 即匿名函数,可以理解为跟C语言的宏类似.例如: >>> max = lambda x, y: x if x > y else y >& ...
- Python Map, Filter and Reduce
所属网站分类: python基础 > 函数 作者:慧雅 原文链接: http://www.pythonheidong.com/blog/article/21/ 来源:python黑洞网 www. ...
- [译]PYTHON FUNCTIONS - MAP, FILTER, AND REDUCE
map, filter, and reduce Python提供了几个函数,使得能够进行函数式编程.这些函数都拥有方便的特性,他们可以能够很方便的用python编写. 函数式编程都是关于表达式的.我们 ...
- Map,Filter和Reduce
转自:https://www.aliyun.com/jiaocheng/444967.html?spm=5176.100033.1.13.xms8KG 摘要:Map,Filter和Reduce三个函数 ...
- python函数和lambda表达式学习笔记
1. python函数 不同于其他语言,python支持函数返回多个值 为函数提供说明文档:help(函数名)或者函数名.__doc__ def str_max(str1, str2): ''' 比较 ...
- Map, filter and reduce
To add up all the numbers in a list, you can use a loop like this: Total is initialized to 0. Each t ...
- Python基础三. 函数、lambda、filter、map、reduce
一.概述 函数, 就是用一些语句组织起来实现一组特定的功能, 用来重复调用. 函数的作用及意义:最大化的重用代码和最小化的代码冗余以及对流程的分解. Python中有哪些函数: 内建的函数 第三方模块 ...
随机推荐
- RDLC 微软报表 导出Excel时产生多个工作表 (worksheet)
. I have added two obejcts data source to Report Viewer. 2. in RDLC i have created two tables and in ...
- each方法的简单使用
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/stric ...
- java深入探究12-框架整合
1.Spring与Hibernate整合 需要配置的就是hibernate和bean.xml 1)关键点:sessionFactory创建交给SpringIOC:session的事务处理交给Sprin ...
- 剑指Offer——链表中倒数第k个节点
Question 输入一个链表,输出该链表中倒数第k个结点. Solution 一种想法就是扫描两边,第一遍求出总的节点个数,第二遍从头开始走n-k个 第二种思想类似于fast-slow指针的方法,f ...
- Avoid RegionServer Hotspotting Despite Sequential Keys
n HBase world, RegionServer hotspotting is a common problem. We can describe this problem with a si ...
- SQL server 2008 T-sql 总结
数据库的实现 1.添加数据:insert [into] 表名 (字段1,字段2,···) values (值1,值2,····) 其中,into可选. 2.修改数据:update 表名 set ...
- QT 使用QPainter 绘制图形 和 世界变换 world transform
1. 绘制椭圆 饼状型 贝塞尔曲线 绘制图像重写方法 void paintEvent(QPaintEvent *event)即可. void Widget::paintEvent(QPaintEve ...
- Boostarp-响应式
一.响应式 响应式介绍 - 响应式布局是什么? 同一个网页在不同的终端上呈现不同的布局等 - 响应式怎么实现的? 1. CSS3 media query 媒体查询 2. JS去控制网页的布局和样式等 ...
- 判断A字符串是B字符串的反转
先将其中一个字符串进行反转操作,然后两个字符串进行判断. 1.反转 /** * 字符串反转 * @param str * @return */ private static String conver ...
- Microsoft Prism安装使用教程 搭建WPF松耦合架构框架
Microsoft Prism安装使用教程 搭建WPF松耦合架构框架 Prism是由微软Patterns & Practices团队开发的项目,目的在于帮助开发人员构建松散耦合的.更灵活.更易 ...