#Python中 (map、filter、reduce)这几个内置方法的用法

1、map  映射

l = [1, 2, 3, 4, 5]

res = map(lambda x:x**2, l)

print(list(res))


>>>[1, 4, 9, 16, 25]

注:

  此时的res必须使用list(res)

  否则只会返回一个对象

 

2、filter 过滤

l = [1, 2, 3, 4, 5]

res = filter(lambda x:x>3, l)

print(list(res))

>>>[4, 5]

 

3、reduce

复制代码
from functools importreduce

l = [1, 2, 3, 4, 5, 6]

res = reduce(lambda x,y:x+y, l)

print(res)



# 1+2+3+4+5+6
>>>21
复制代码

 

posted @   wellplayed  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示