day16 函数式编程

#高阶函数
1#函数接收的参数是一个函数名 2#返回值中包含函数

# 把函数当作参数传给另外一个函数
# def foo(n): #n=bar
# print(n)
#
# def bar(name):
# print('my name is %s' %name)
#
# # foo(bar)
# # foo(bar())
# foo(bar('alex'))

#返回值中包含函数
def bar():
print('from bar')
def foo():
print('from foo')
return bar
n=foo()
n()
def hanle():
print('from handle')
return hanle
h=hanle()
h()



def test1():
print('from test1')
def test2():
print('from handle')
return test1()
map函数
map(function, iterable, ...)

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

filter函数

对指定序列执行过滤操作。

其定义:

filter(函数 function, 序列 sequence)

function接收一个参数,返回值为布尔值。序列可以是列表、元组、字符串。

filter()以序列参数sequence中的每个元素为参数调用function函数,调用结果为True的元素最后将作为filter()函数的结果返回。
————————————————
版权声明:本文为CSDN博主「所爱隔山海。」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39969226/article/details/100173577

movie_people=['aaa_sb','bbb_sb','ccc','ddd_sb']
# def sb_show(n):
#     return n.endswith('sb')
def filter_test(func,array):
    ret=[]
    for p in array:
        if not func(p):
            ret.append(p)
    return ret
print(list(filter(lambda n:n.endswith('sb'),movie_people)))
reduce函数
reduce(function, iterable[, initializer])

reduce() 函数会对参数序列中元素进行累积。                             

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

>>>def add(x, y) :            # 两数相加
...     return x + y
... 
>>> reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
15
>>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
15

猜你喜欢

转载自www.cnblogs.com/douyunpeng/p/12626735.html
今日推荐