python--004--函数(map、filter、reduce)

1. map 函数
# 实现指定列表自增1
num_1 = [1, 2, 10, 5, 6, 8]

def map_test(func, array):
    ret = []
    for i in array:
        res = func(i)
        ret.append(res)
    return ret


print(map_test(lambda x: x + 1, num_1))
# 这就是python提供的map所实现的功能
print('内置函数map,处理结果', map(lambda x: x + 1, num_1))
# output: [2, 3, 11, 6, 7, 9]
# 内置函数map,处理结果 <map object at 0x00000000027933C8>    ,返回的是迭代器,只能处理一次
res = map(lambda x: x + 1, num_1)
print(list(res))
# output;[2, 3, 11, 6, 7, 9]


2、 filter函数
movie_people = ['peiqi_ab', 'qiaozhi_ab', 'suxi_ab', 'cat']
print(filter(lambda n: n.endswith('ab'), movie_people))
print(list(filter(lambda n: n.endswith('ab'), movie_people)))

3、reduce函数 ---python2中直接用
from functools import reduce ---python3中使用reduce函数需要导入

from functools import reduce

num_1 = [1, 2, 10, 5, 6, 8]
print(reduce(lambda x, y: x + y, num_1, 1))     # 最后一个值为附的初始值


4、区别

map:处理序列中的每个元素,得到的结果是一个“列表”,该“列表”元素个数及位置与原来一样
filter:遍历序列中的每个元素,判断每个元素得到一个布尔值。如果是true则保留
reduce:处理一个序列,然后把序列进行合并操作



猜你喜欢

转载自www.cnblogs.com/jinf/p/10633903.html