map函数
map函数的结构为 map(处理方法,可迭代对象) ,相当于for循环遍历可迭代对象中的每一个元素,对每一个元素做指定操作,得到一个和原始数据顺序相同的迭代器。(在Python3中最终得到的结果是一个迭代器,可以用list()函数转化为列表,在Python2中map函数的结果就是一个列表。)
map函数实例
原始方法:
def map_test(array):
ret = []
for i in array:
res = i - 1
ret.append(res)
return ret
print(map_test(l))
采用下面这种方法较第一种方法更灵活,批量修改时只需要修改被调用函数即可。
l = [1, 2, 10, 11]
def reduce_one(x):
return x - 1
def map_test(func, array):
ret = []
for i in array:
res = func(i)
ret.append(res)
return ret
print(map_test(reduce_one, l))
采用匿名函数的方式会在灵活的基础上更加简洁:
l = [1, 2, 10, 11]
def map_test(func, array):
ret = []
for i in array:
ret.append(func(i))
return ret
print(map_test(lambda x: x - 1, l))
以map函数形式:
注意map函数返回的结果是一个迭代器
l = [1, 2, 10, 11]
res = map(lambda x: x - 1, l)
print(list(res))
filter函数
filter函数的结构为 filer(结果为布尔值的函数,可迭代对象),相当于for循环遍历可迭代对象中的每个元素,对每个元素进行指定判断,如果结果为True则保留该元素,所得结果为一个迭代器。
filter函数实例
原始方法:
movie_people = ["ALucky", "AAlex", "ADog", "MB", "Adsa", "YY"]
def filter_test(array):
res = []
for i in array:
if not i.startswith("A"):
res.append(i)
return res
print(filter_test(movie_people))
较为灵活的方法:
def remove_A(x):
return x.startswith("A")
def filter_test(func, array):
ret = []
for i in array:
if not func(i):
ret.append(i)
return ret
movie_people = ["ALucky", "AAlex", "ADog", "MB", "Adsa", "YY"]
print(filter_test(remove_A, movie_people))
匿名函数写法:
def filter_test(func, array):
ret = []
for i in array:
if not func(i):
ret.append(i)
return ret
movie_people = ["ALucky", "AAlex", "ADog", "MB", "Adsa", "YY"]
print(filter_test(lambda x: x.startswith("A"), movie_people))
filter函数写法:
movie_people = ["ALucky", "AAlex", "ADog", "MB", "Adsa", "YY"]
res = filter(lambda x: not x.startswith("A"), movie_people)
print(list(res))
reduce函数
reduce函数结构为 reduce(函数,可迭代对象,初始值),相当于for遍历可迭代对象中的每一个元素,将所有元素和初始值按照指定函数的操作执行,最终返回一个值。在Python3中reduce函数中调用reduce函数必须先导入模块,即以from functools import reduce开头。
reduce函数实例
原始方法:
def reduce_test(array, init=None):
if init == None:
res = array.pop(0)
for i in array:
res *= i
return res
else:
res = init
for i in array:
res *= i
return (res)
l = [1, 2, 3, 100]
print(reduce_test(l))
较灵活的方法:
def multi(x, y):
return (x * y)
def reduce_test(func, array, init=None):
if init == None:
res = array.pop(0)
for i in array:
res = func(res, i)
else:
res = init
for i in array:
res *= func(res, i)
return res
l = [1, 2, 3, 100]
print(reduce_test(multi, l))
匿名函数的写法:
def reduce_test(func, array, init=None):
if init == None:
res = array.pop(0)
for i in array:
res = func(res, i)
else:
res = init
for i in array:
res = func(res, i)
return res
l = [1, 2, 3, 100]
print(reduce_test(lambda x, y: x * y, l))
reduce函数:
注意必须先导入模块
l = [1, 2, 3, 100]
from functools import reduce
res = reduce(lambda x, y: x * y, l)
print(res)