# ### 高阶函数 :能够把函数当成参数传递的就是高阶函数 (map reduce sorted filter ) # map ''' map(func,iterable) 功能:把iterable里面的数据一个一个的拿出来放到func函数中进行处理,最后把处理的结果返回到迭代器中 参数: func : 自定义函数 或 内置函数 iterable: 可迭代性数据 (常用:容器类型数据,range对象,迭代器) 返回值:迭代器 ''' # 1. ["1","2","3","4"] => [1,2,3,4] listvar = ["1","2","3","4"] ''' # 普通写法 lst = [] for i in listvar: res = int(i) lst.append(res) print(lst) ''' from collections import Iterator , Iterable it = map(int,listvar) print(isinstance(it,Iterator)) print(isinstance(it,Iterable)) print(it) # (1)使用for循环遍历迭代器 ''' for i in it: print(i) ''' # (2) 使用next获取迭代器中的数据 '''next调用迭代器中的数据,是单项不可逆,一条路走到黑''' ''' res = next(it) print(res) res = next(it) print(res) res = next(it) print(res) res = next(it) print(res) ''' # (3) 使用list强转迭代器(瞬间得到迭代器中的所有数据) res = list(it) print(res) # 2. [1,2,3,4,5] => [1,4,9,16,25] # 普通写法: listvar = [1,2,3,4,5] lst = [] for i in listvar: res = i ** 2 lst.append(res) print(lst) ''' map 如果是自定义函数,一定要有返回值 代码解析: 首先把listvar当中的第一个值1拿到func当中进行处理,返回1扔到迭代器里 然后把listvar当中的第二个值2拿到func当中进行处理,返回4扔到迭代器里 然后把listvar当中的第三个值3拿到func当中进行处理,返回9扔到迭代器里 .. 依次类推,直到把列表里面的数据全部拿完为止. ''' def func(n): return n ** 2 it = map(func,listvar) print(isinstance(it,Iterator)) listvar = list(it) print(listvar) # 3. {97:"a",98:"b",99:'c',100:'d',101:"e"} {"c","a","b"} => [99,97,98] ''' # 普通写法: dic = {97:"a",98:"b",99:'c',100:'d',101:"e"} dic2 = {} # 反转字典 for a,b in dic.items(): dic2[b] = a print(dic2) lst = ["c","a","b"] lst2 = [] #{'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101} for i in lst: res = dic2[i] lst2.append(res) print(lst2) ''' def func(n): dic = {97:"a",98:"b",99:'c',100:'d',101:"e"} dic2 = {} # 反转字典 for a,b in dic.items(): dic2[b] = a #{'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101} return dic2[n] it = map(func,["c","a","b"]) print(isinstance(it,Iterator)) lst = list(it) print(lst)