filter
def my_map(func, array): new_array = [] for i in array: new_array.append(func(i)) return new_array print(my_map(lambda x: x > 5, range(10))) print(list(map(lambda x: x > 5, range(10)))) 结果: [False, False, False, False, False, False, True, True, True, True] [False, False, False, False, False, False, True, True, True, True] |
map
def my_filter(func, array): new_array = [] for i in array: if func(i): new_array.append(i) return new_array print(my_filter(lambda x: x > 5, range(10))) print(list(filter(lambda x: x > 5, range(10)))) 结果: [6, 7, 8, 9] [6, 7, 8, 9] |
reduce
from functools import reduce def my_reduce(func, array, init): list_array = list(array) if init is None: res = list_array.pop(0) else: res = init for i in list_array: res = func(res, i) return res print(my_reduce(lambda x, y: x + y, range(5), 10)) print(reduce(lambda x, y: x + y, range(5), 10)) 结果: 20 20 |