函数
当一个函数的返回值是另一个函数的函数名时, 只是返回该函数的内存地址, 该函数的作用域不会发生改变.
- 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)
来源: http://www.bubuko.com/infodetail-2621527.html