函数式编程(九)——map,filter,reduce

编程方法论

面向过程:按照一个固定的流程去模拟解决问题的流程

函数式:编程语言定义的函数 + 数学意义的函数

    y = 2*x + 1 函数用编程语言实现

    def fun(x):

      return 2*x + 1

面向对象

函数式编程

1. 不可变:不用变量保存状态,不可修改变量
# 函数式编程
# 1. 不可变:不用变量保存状态,不可修改变量

# 非函数式
a = 1
def test1():
    global a
    a += 1
    return a

# 函数式
n = 1
def test2():
    return n + 1

 

2.函数即“变量”

  a.函数可以当参数传递

  b.返回值可以式函数名

def foo(n):
    print(n)

def bar(name):
    print('my name is %s' % name)
    
foo(bar)
foo(bar('zhangsan'))

输出:

<function bar at 0x0000024E4B385C80>
my name is zhangsan
None

 

3.高阶函数 :1.函数接受的参数是一个函数名 2.返回值是函数名,两个条件满足一个就是高阶函数

# 把函数当中参数传给另外一个函数

def foo(n):
    print(n)


def bar(name):
    print('my name is %s' % name)


foo(bar)
foo(bar('zhangsan'))

# 返回值中包含函数


def test3():
    print('from test3')


def handle():
    print('from handle')
    return test3()


handle()

 

4.尾调用

  在函数的最后一步调用另外一个函数(最后一行不一定是最后一步),调用函数的栈状态不需要保存,可以用来优化递归函数,俗称:尾递归

 

map函数

# map函数

# num_l = [1, 2, 3, 4] #求平方
# ret = []
# for i in num_l:
#     ret.append(i**2)
# print(ret)

def add_one(x):
    return x + 1


def reduce_one(x):
    return x - 1


def pingfang(x):
    return x**2


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


num_2 = [1, 2, 3, 4]
ret = map_test(add_one, num_2)
print(ret)
ret = map_test(reduce_one, num_2)
print(ret)
ret = map_test(pingfang, num_2)
print(ret)
ret = map_test(lambda x:x+2, num_2)     # lambda方式
print(ret)

res = map(lambda x: x + 2, num_2)       # 内置map函数 ,返回可迭代对象
print(res)      # <map object at 0x000001F62514BF60>
print(list(res))    # [3, 4, 5, 6]
print(list(map(reduce_one, num_2)))     # [0, 1, 2, 3]

msg = 'hello'
print(list(map(lambda x: x.upper(), msg)))

 

filter函数

# filter
people = ['sb_A', 'sb_B', 'C_sb', 'D_sb']


def end_with_sb(n):
    return n.endswith('sb')


def start_with_sb(n):
    return n.startswith('sb')


def filter_test1(array):
    res1 = []
    for p in array:
        if not p.startswith('sb'):
            res1.append(p)
    return res1


def filter_test2(fun, array):
    res1 = []
    for p in array:
        if not fun(p):
            res1.append(p)
    return res1


print(filter_test1(people))
print(filter_test2(start_with_sb, people))
print(filter_test2(end_with_sb, people))
print(filter_test2(lambda n1: n1.endswith('sb'), people))
print('*'*20)
ret2 = filter(lambda n2: n2.endswith('sb'), people)  # 内置函数,返回一个内存地址,保存了list地址
print(list(ret2)) # ['C_sb', 'D_sb']
ret3 = filter(lambda n2: not n2.endswith('sb'), people)
# lambda n2: n2.endswith('sb') 返回一个bool值,为true则保留
print(list(ret3)) # ['sb_A', 'sb_B']

 

info = [{'name': 'a', 'score': 80},
        {'name': 'b', 'score': 90},
        {'name': 'c', 'score': 90}]
res = filter(lambda i: i['score'] < 90, info)
print(list(res)) # [{'name': 'a', 'score': 80}

 

 

reduce函数

# reduce函数
num_3 = [1, 2, 3, 100]


def reduce_test(fun, array, init=None):
    if init is None:
        res = array.pop(0)
    else:
        res = init
    for num in array:
        res = fun(res,num)
    return res


res = reduce_test(lambda x, y: x*y, num_3)
print(res)  # 600
res = reduce_test(lambda x, y: x*y, num_3, 10)
print(res)  # 6000

from functools import reduce
num_4 = [1, 2, 3, 100]
res = reduce(lambda x, y: x+y, num_4, 10)
print(res) # 116

 

posted @ 2019-02-16 22:08  狂奔~  阅读(355)  评论(0编辑  收藏  举报