【384】reduce归纳、map映射、filter筛选 的用法
参考:4. Map, Filter and Reduce — Python Tips 0.1 documentation
Map:映射,对于列表的每个元素进行相同的操作
filter:筛选,筛选列表中满足某一条件的所有元素
reduce:归纳,连续操作,连加、连乘等
python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.
reduce的用法
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from functools import reduce reduce ( lambda x,y: x + y, [ 1 , 2 , 3 ]) reduce ( lambda x,y: x + y, [ 1 , 2 , 3 ], 9 ) reduce ( lambda x,y: x * y, [ 1 , 2 , 3 , 4 ]) reduce ( lambda x,y: x * y, [ 1 , 2 , 3 , 4 ], 5 ) reduce ( lambda x,y: x * * y, [ 2 , 3 , 4 ]) output: 6 15 24 120 4096 |
Example from Ed of COMP9021
question:
For instance, dict1 = {'Lucy' : 'I am a Knight', 'Laser':'I am a Knaves'}
list1 = [(0,0), (0,1), (1,0),(1,1)]
how do I put the output like this:
{'Lucy' : 0, 'Laser':0}
{'Lucy' : 0, 'Laser':1}
{'Lucy' : 1, 'Laser':0}
{'Lucy' : 1, 'Laser':1}
answers:
1 2 3 4 5 | dict1 = { 'Lucy' : 'I am a Knight' , 'Laser' : 'I am a Knaves' } list1 = [( 0 , 0 ), ( 0 , 1 ), ( 1 , 0 ),( 1 , 1 )] answer = [i for i in map ( lambda x:{[key for key in dict1][ 0 ]:x[ 0 ], [key for key in dict1][ 1 ]:x[ 1 ]}, list1)] for i in answer: print (i) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)