Python 函数lambda(), filter(), map(), reduce()
2024-10-06 15:37:43
1 filter
filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)
比如
def f(x): return x % 2 != 0 and x % 3 != 0
x = filter(f, range(2, 25))
也可以用推导式这样写
x = [x for x in range(2, 25) if x % 2 != 0 and x % 3 != 0 ]
print ( x )
也可以用filter + lambda 这样写
x = filter( lambda x:x % 2 != 0 and x % 3 != 0, range(2, 25))
print ( x )
2 map
map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回,比如
data = map(lambda x: x*x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)
输出 [1, 4, 9, 16, 25, 36, 49, 64, 81]
再比如把列表的数字全部转为字符串
data = map(lambda x: str(x), [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)
3 reduce
reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
比方说对一个序列求和,就可以用reduce实现
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
最新文章
- iperf交叉编译:
- 短视频APP+不同类型社交应用发展分析+化妆品电商
- jquery.roundabout.js实现3D图片层叠旋转木马切换
- java抽象类和接口的区别
- shell问题(转)
- 第一篇HBuilder在这里!
- 关于STM32库中 __IO 修饰符(volatile修饰符,反复无常的意思)
- 模仿Word中组织结构图的特点生成流程图
- bzoj2005: [Noi2010]能量采集
- javascript string对象方法总结
- Java设计模式(五)Prototype原型模式
- Qt5中this application has requested the runtime to terminate it in an unusual way 无法运行问题的解决
- 深入理解Java虚拟机之JVM垃圾回收随笔
- js判断一个字符串是以某个字符串开头
- h5在手机端实现简单复制
- ABBYY PDF Transformer+安装教程
- 批量将某一目录下的.py文件改为.txt格式文件
- java mysql的latin1转UTF-8
- 【原创】Apache ab测试时出现:apr_socket_recv ";connection reset by peer"; 104
- ubuntu 14.4 apache2 django