Python函数,匿名函数,高阶函数,内置函数——08

函数

当一个函数的返回值是另一个函数的函数名时,只是返回该函数的内存地址,该函数的作用域不会发生改变。

name = 'winsodm'
def test():
    name = 'xl'
    print('in the test')

def test1():
    print('in the test1')
    return test

res = test1()
res()
#结果是:
name = 'xl'
'in the test'
#这里返回的test 之后运行 还是输入test里的变量name的值,而不是全部变量的name='winsdom'

匿名函数

lambda关键字

格式:lambda 形参:return值

lambda x:x+1
lambda x,y,z:(x+1,y+1,z+1)

匿名函数,使用完后自动释放内存空间。

高阶函数

1、把函数当作参数传递给另一个函数(函数接收的参数是一个函数名)

2、返回值中包含函数

符合以上两个规则中任意一个的函数叫高阶函数

def test():
    name = 'xl'
    print('in the test')#非高阶函数

def test1():
    print('in the test1')#高阶函数
    return test

map内置函数

传入一个函数,一个可迭代对象,遍历可迭代对象,将可迭代对象用传入的函数作一个处理并返回操作结果

num_l = [1,3,5,2,10,4,6,9,8]#定义一个列表

new_num_l =list(map(lambda x:x+1,num_l))#传入一个自增1的匿名函数和一个列表,并将其转换成list形式赋值给new_num_l这个新列表
#结果是:
print(new_num_l)
new_num_l = [2, 4, 6, 3, 11, 5, 7, 10, 9]

自己实现:

num_l = [1,3,5,2,10,4,6,9,8]#定义一个列表

def add_one(x):
    #定义一个自增1的函数    
    return x +1
def map_1(fucn,l):
    new_num_l = []#创建一个新列表
    for i in l:
        new_num_l.append(fucn(i))#遍历num_l,使用传入的函数自增1,然后加到新列表new_num_l当中去
    return new_num_l#返回新列表
new_num_l = map_1(add_one,num_l)#接收新列表
#new_num_l = map_1(lambda x:x+1,num_l)  #也可以直接传入匿名函数
print(new_num_l)
#结果是:
new_num_l = [2, 4, 6, 3, 11, 5, 7, 10, 9]

例:使用map内置函数将字符串转换成列表的形式,并且全部大写

name = 'winsdom'
name_list = list(map(lambda x:x.upper(),name))
print(name_list)
#结果是:
name_list = ['W', 'I', 'N', 'S', 'D', 'O', 'M']

filter内置函数

传入一个函数,一个可迭代对象,遍历可迭代对象,将可迭代对象里的每一个元素做一个bool值判断,如果是Ture则保留下来

name_list = ['xlc','hhc','hzzc','hc','winsdom']
print(list(filter(lambda x:x.endswith('m'),name_list)))
#结果是:
['winsdom']
name_list = ['xlc','hhc','hzzc','hc','winsdom']
print(list(filter(lambda x:not x.endswith('c'),name_list)))
#结果是:
['winsdom']

自己实现:

name_list = ['xlc','hhc','hzzc','hc','winsdom']
def end_with(x):
    #定义一个判断是否以c结尾的函数
    return x.endswith('c')
def filter_1(func,array):
    new_name_list = []#创建一个新列表
    for n in array:
        if not func(n):#判断  如果不是以c结尾则加入新列表
            new_name_list.append(n)
    return new_name_list

new_name_list = filter_1(end_with,name_list)
#new_name_list = filter_1(lambda x:x.endswith('c'),name_list)#用匿名函数直接传入,由于filter_1里写了not 所以这里的匿名函数不需要写not
print(new_name_list)
#结果是:
new_name_list = ['winsdom']

reduce内置函数

传入一个函数,一个可迭代对象,一个默认参数,将可迭代对象压缩成一个值返回

reduce在python2中可以直接使用,在python3中需要import

from functools import reduce

num_l = [1,3,5,100]
num = reduce(lambda x,y:x*y,num_l,2)
print(num)
#结果是:
num = 3000

自己实现:

from functools import reduce

num_l = [1,3,5,100]

def reduce_1(func,array,init = None):#init表示一个初始值
    if init == None:
        res = array.pop(0)
    else:
        res = init
    for i in  array:
        res = func(res,i)
    return res

res = reduce_1(lambda x,y:x*y,num_l,100)
print(res)

猜你喜欢

转载自www.cnblogs.com/winsdom/p/9102425.html
今日推荐