from functools import reduce # map函数,可以将一个列表内的元素代入指定的函数内,运算后生成一个新的列表 # 实现批量操作功能 list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] def f1(x): return x**2 def f2(x): return x + 1 def f3(x): return x - 1 def map_test(func, data): list2 = [] for i in data: result = func(i) list2.append(result) return list2 print(map_test(f1, list1)) print(map_test(f2, list1)) # map函数 # 使用方法: map(函数, 可迭代处理对象) res = map(f1, list1) # 返回结果,一个可迭代的map类型物理内存地址(迭代器) print(res) # 只能取值一次,取值完后再调用就是空 #for i in res: # print(i) # for循环调用完后,这里再次调用就会显示一个空列表 # python2中,不需要通过list函数转换,直接返回结果就是列表 # python3中,需要通过list函数转换才能显示,否则显示的是迭代器的物理地址 即直接 print(res) print(list(res)) name_list = "zhouweoyuan" print(list(map(lambda x:x.upper(), name_list))) # filter函数和map函数类似,也是接受一个函数一个序列作为参数 # 不同的是:将序列中每个元素代入到传入的函数中后,返回的是布尔值,根据布尔值决定保留还是丢弃 # 实现批量筛选功能 list3 = ["aaa", "abc", "bbb"] def startswith_a(arrapt): return arrapt.startswith("a") # 返回结果和map一样,python3中是一个迭代器类型 print(list(filter(startswith_a, list3))) # 删除列表中的空字符 list4 = ["a", "b", "c", "", " "] def not_null(arrapt): # strip()方法内可以指定去除的字符,如果不指定则去除空字符(包括\n \t \r "") return arrapt.strip() print(list(filter(not_null, list4))) # reduce函数 # reduce参数中的函数必须能接收两个参数 list5 = [2, 2, 3, 100] def reduce_test(arrapt): res = 0 for i in arrapt: res += i return res def cheng(x, y): return x * y def reduce_test_2(func, arrapt): # 使用pop方法,从列表中弹出0索引上的值,赋给res。 此时列表中剩三个值 res = arrapt.pop(0) for i in arrapt: res = func(res, i) return res print(reduce_test_2(cheng, list5)) #print(list5.pop(1)) print(list5) # reduce得到的结果是一个最终处理的值,这个值可以赋给变量 result = reduce(cheng, list5) print(reduce(cheng, list5)) print(result) # 总结 people_list = [ {"name": "aaa", "age": 1000}, {"name": "abc", "age": 10000}, {"name": "a", "age": 8000}, {"name": "ddd", "age": 18} ] # map批量操作列表中的字典元素 print(list(map(lambda p:p["age"] + 10, people_list))) # filter保留100岁以下的人 print(list(filter(lambda p:p["age"] <= 100, people_list))) print(list(filter(lambda p:p["name"].startswith("a"), people_list))) # reduce算出总年龄 #def sum_age(p): # sum_age = p.pop(0)["age"] # for value in p: # sum_age = sum_age + value["age"] # return sum_age # #print(sum_age(people_list)) print(list(map(lambda x:x["age"]+10, people_list))) # 这里套用map函数就可以对map的处理结果进行reduce再处理 print(reduce(lambda x,y:x+y, (map(lambda x:x["age"], people_list)))) print(reduce(lambda x,y:x+y, range(0,101)))