博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

py-day3-6 python map函数

Posted on 2019-02-27 10:02  MJ-majun  阅读(150)  评论(0编辑  收藏  举报
map函数 :处理序列中的每个元素,得到的结果是一个列表,该列表元素个数及位置与原来一样

#
# 求列表里元素的平方 (原始方法) num_1=[1,2,13,5,8,9] res =[] for i in num_1: res.append(i**2) print('打印结果:',res) 打印结果: [1, 4, 169, 25, 64, 81] 有多个列表求里面元素的平方 (定义成函数) num_1=[1,2,13,5,8,9] def test(array): res =[] for i in num_1: res.append(i**2) return res end1 = test(num_1) end2 = test(num_1) # 以后用直接调用函数就可以了 print('打印结果:',end1) print('打印结果:',end2) 打印结果: [1, 4, 169, 25, 64, 81] 打印结果: [1, 4, 169, 25, 64, 81] 提的需求就是功能,功能就要封装在函数里 num_1=[1,2,13,5,8,9] def reduce_1(x): # 定义自减1函数 return x-1 def add_1(x): # 定义自增1函数 return x+1 def test(func,array): res =[] for i in num_1: ret=func(i) res.append(ret) return res print('自增1的结果:',test(add_1,num_1)) print('自减1的结果:',test(reduce_1,num_1)) 自增1的结果: [2, 3, 14, 6, 9, 10] 自减1的结果: [0, 1, 12, 4, 7, 8] # 终极版本 最简单的.使用匿名函数同样可以做到 num_1=[1,2,13,5,8,9] def test(func,array): res =[] for i in num_1: ret=func(i) res.append(ret) return res print('自增1的结果:',test(lambda x:x+1,num_1)) print('自减1的结果:',test(lambda x:x-1,num_1)) print('平方的结果:',test(lambda x:x**2,num_1)) print('除2的结果:',test(lambda x:x/2,num_1)) 自增1的结果: [2, 3, 14, 6, 9, 10] 自减1的结果: [0, 1, 12, 4, 7, 8] 平方的结果: [1, 4, 169, 25, 64, 81] 除2的结果: [0.5, 1.0, 6.5, 2.5, 4.0, 4.5] 内置函数map函数 num_1=[1,2,13,5,8,9] def test(func,array): res =[] for i in num_1: ret=func(i) res.append(ret) return res print('匿名函数的处理结果:',test(lambda x:x+1,num_1)) ret = map(lambda x:x+1,num_1) print('内置函数map的处理结果:',list(ret)) 匿名函数的处理结果: [2, 3, 14, 6, 9, 10] 内置函数map的处理结果: [2, 3, 14, 6, 9, 10] map函数 还适用与自己设定的函数 num_1=[1,2,13,5,8,9] def reduce_1(x): # 定义自减1函数 return x-1 def add_1(x): # 定义自增1函数 return x+1 def test(func,array): res =[] for i in num_1: ret=func(i) res.append(ret) return res ret = map(reduce_1,num_1) ret1 = map(add_1,num_1) print('map处理自减1的结果:',list(ret)) print('map处理自加1的结果:',list(ret1)) map处理自减1的结果: [0, 1, 12, 4, 7, 8] map处理自加1的结果: [2, 3, 14, 6, 9, 10] map还以可以迭代其他对象 msg ='majunnihao' #(例如小写转换成大写) t = map(lambda x:x.upper(),msg) print(list(t)) ['M', 'A', 'J', 'U', 'N', 'N', 'I', 'H', 'A', 'O']