1.Map函数 - 列表解析
①.map()函数解析
(1).python源码信息
C:\Users\ArSang>python Python 3.6.3rc1 (v3.6.3rc1:d8c174a, Sep 19 2017, 16:39:51) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(map) Help on class map in module builtins: class map(object) | map(func, *iterables) --> map object | | Make an iterator that computes the function using arguments from | each of the iterables. Stops when the shortest iterable is exhausted. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.
(2).map()接收一个函数和一个可迭代对象list数组,并通过函数方法去迭代list中的每个元素从而得到并返回一个新的list
p_list = [1, 2, 3, 4] # 构建函数 def f(x): """ 实现给list中的每个元素+2 :return: """ return x + 2 ''' 3.x中返回需要添加返回类型,spe=list(),2.x中不需要,在3.0中map函数仅仅是创建一个待运行的命令容器,只有其他函数调用他的时候才会返回结果 Python 2.x 返回列表 Python 3.x 返回迭代器 ''' spe = list(map(f, p_list)) print(spe) # 返回新的list print(id(p_list)) # 查询原数组内存地址 print(id(spe)) # 查询新数组内存地址 """spe≠p_list"""
(3).使用for循环迭代实现
l = [1, 2, 3, 4] def add_list(x): return x + 2 def map_list(f, arr_list): temp = [] for i in arr_list: rep = f(i) temp.append(rep) return temp res = map_list(add_list, l) print(res) # 返回新的数组 print(id(l)) # 查询原数组内存地址 print(id(res)) # 查询新数组非常地址
(4).列表解析for与map
''' Python下:for效率 < map()效率 '''
②.map()函数也可接受多参数的函数
l = [1, 2, 3, 4] # 将l列表加2后返回一个新列表 rep = map(lambda x: x + 2, l) print(list(rep)) a = [1, 2, 3, 4] b = [5, 6, 7, 8] # 将a,b两个数组中的元素相乘,返回一个新的列表元素 ret_list = map(lambda x, y: x * y, a, b) print(list(ret_list))
③普遍函数与匿名方法:
a = [1, 2, 3, 4] b = [5, 6, 7, 8] def add_fun(number1, number2): number1 += number2 return number1 def sum_list(): # 普遍函数 res1 = map(add_fun, a, b) # 匿名函数 res2 = map(lambda x: x ** 2, [x for x in range(10)]) print(list(res1), list(res2)) if __name__ == '__main__': sum_list()
④其他应用
a = ['YSDSASD', 'lsfrr', 'tGdDSd', 'Sdddd'] def fun(f): """ 将列表的第一个字母偶同意大写,后面的字母统一小写 :return: """ return f[0:1].upper() + f[1:].lower() if __name__ == '__main__': lit = map(fun, a) print(list(lit))
2.reduce()函数 - 递归计算
①reduce()函数解析
(1).python3中源码解析
from functools import reduce print(help(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.
(2).reduce()函数取值规则:
# python3中使用reduce需要导入 from functools import reduce a = [1, 2, 3, 4] app_list = reduce(lambda x, y: x * y, a) num_list = reduce(lambda x, y: x * y, range(1, 5)) print(app_list) print(num_list) ''' a = [1, 2, 3, 4] 第一次相乘:x([0])*y([1]) 第二次相乘:x(([0]*[1])result)*y([2]) 第三次相乘:x(([0]*[1]*[2])result)*y([3]) ..... '''
②其他应用
# python3中使用reduce需要导入 from functools import reduce a = [1, 2, 3] ''' x * y的单结果+1 第一次计算:1 *2 + 1 = result 第二次计算:(result*3)+1 = resulttwo 第三次计算:(resulttwo*4)+1 .... ''' app_list = reduce(lambda x, y: x * y+1, a) # 第三参数:5 x*y的总结果*5 num_list = reduce(lambda x, y: x * y, range(1, 5), 5) print(app_list) print(num_list)
3.filter()函数 - 过滤器
①filter()函数解析
(1).python源码解析
C:\Users\ArSang>python Python 3.6.3rc1 (v3.6.3rc1:d8c174a, Sep 19 2017, 16:39:51) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(filter) Help on class filter in module builtins: class filter(object) | filter(function or None, iterable) --> filter object | | Return an iterator yielding those items of iterable for which function(item) | is true. If function is None, return the items that are true. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.
②filter()返回值
# 列表解析的方式 b = [i for i in range(10) if i > 5 and i < 8] print(list(b)) # filter()函数方式 b = filter(lambda x: x > 5 and x < 8, range(10)) print(list(b)) ''' 1.filter()函数首先需要返回一个bool类型的函数 2.如上示例,判断x是否大于5且小于8,最后将这个函数作用到range(10)的每个函数中,如果为True,则将满足条件的元素组成一个列表返回 '''
③其他应用
(1).删除None列表元素
def is_empty(s): """ 删除None元素字符 :return: """ return s and len(s.strip()) > 0 if __name__ == '__main__': b = ['', 'str', ' ', 'end', '', ''] print(list(filter(is_empty, b)))
(2).匿名函数和自定义函数
import random # 自定义函数 ''' def fun(x): return x * 2 arr_list = [] for i in range(10): arr_list.append(random.randint(1, 20)) print(arr_list) if __name__ == '__main__': print(list(filter(fun, arr_list))) ''' # 匿名函数 arr_lst = [] for i in range(10): arr_lst.append(random.randint(1, 20)) print(arr_lst) if __name__ == '__main__': print(list(filter(lambda x: x * 2, arr_lst)))