Python基础-高阶函数-Map-Reduce

来源:互联网 发布:powershell 连接linux 编辑:程序博客网 时间:2024/06/05 09:17

Map函数

map()函数接受2个参数
1. 参数 函数
2. 参数 Iterable

示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# map() 函数的使用# 转换为字符串def funtion(x):    return str(x)def test():    mList = [1,2,3,4,5]    # ('List ', [1, 2, 3, 4, 5])    print("List ", mList)    # Map函数的使用:函数, Iterator    # ('Map ', ['1', '2', '3', '4', '5'])    mMap = map(funtion, [1,2,3,4,5])    print("Map ", mMap)# 运行测试程序    test()

运行结果

D:\PythonProject>python run.py('List ', [1, 2, 3, 4, 5])('Map ', ['1', '2', '3', '4', '5'])

我的理解是,管他的能用就行,知道怎么传参,传出什么结果就行了。结果是以一个新的Iterator,项目用到的时候才是关键

Reduce用法

reduce把一个函数作用在一个序列[a,b..]上,这个函数必须接受2个参数,reduce把结果继续和序列的下一个元素做累积计算,效果如下

reduce(f(x, y), [a, b]) = f(a, b)

我的理解就是传递2个类似递归函数的,详见下面demo,看代码理解得快

实例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# Python Reduce用法# reduce(f(x, y), [a, b]) = f(a, b)# reduce(f(x, y), [a, b, c]) = f(f(a, b),c)# 2 个参数的函数def function(x, y):    return x +ydef reduceTest():    # reduce(f(x, y), [a, b]) = f(a, b)    # f(x, y) = f(1, 2) = 1 + 2 = 3    # 预测值 result = 3    result = reduce(function, [1, 2])    # 实际答案 3    print(result)    # reduce(f(x, y), [a, b, c]) = f(f(a, b),c)    # 第一步f(x, y) = f(1, 2) = 1 + 2 = 3    # 第二步f(x, y) = f(3, 3) = 1 + 2 = 6    result = reduce(function, [1, 2,3])    # 实际答案 6    print(result)reduceTest()

运行结果

D:\PythonProject>python run.py36
原创粉丝点击