内置函数
注:查看详细https://docs.python.org/3/library/functions.html#next
匿名函数
1 def calc(x): 2 return x+1 3 4 5 print(calc(10)) 6 # print(lambda x:x+1) # 匿名函数内存地址 7 8 func = lambda x: x + 1 9 print(func(10))
高阶函数
满足任意一个条件:
1、函数的传入参数是一个函数名
2、函数的返回值是一个函数名
1.map内置函数 map(func, *iterables) --> map object
1 num_l = [1, 2, 3, 4, 5, 6] 2 # lambda x: x+1 3 4 5 def add_one(x): 6 return x+1 7 8 9 def map_test(func, array): 10 """ 11 模拟map内置函数 12 :param func: 传入的参数进行处理方法 13 :param array: 传入可迭代的对象 14 :return: 15 """ 16 ret = [] 17 for i in array: 18 res = func(i) 19 ret.append(res) 20 return ret 21 22 23 print(map_test(add_one, num_l)) 24 print(map_test(lambda x: x+1, num_l)) 25 res = map(lambda x: x+1, num_l) 26 print(list(res)) 27 28 29 name = 'eric' 30 v = map(lambda x: x.upper(), name).__iter__() # 把对象转成可迭代对象 遵行迭代协议 31 r = v.__next__() # next直到StopIteration 32 print(r) 33 34 # print(list(map(lambda x: x.upper(), name)))
2.filter函数
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 movie_person = ['eric_sb', 'alex_sb', 'lhf'] 6 7 8 def sb_show(x): 9 return x.endswith('_sb') 10 11 12 def filter_test(func, array): 13 ret = [] 14 for p in array: 15 if not func(p): 16 ret.append(p) 17 return ret 18 19 20 print(filter_test(sb_show, movie_person)) 21 22 print(list(filter(lambda x: not x.endswith('_sb'), movie_person)))
3.reduce函数
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 from functools import reduce 6 7 num_l = [1, 2, 3, 100] 8 9 10 def reduce_test(func, array, init=None): 11 if init is None: 12 res = array.pop(0) 13 else: 14 res = init 15 for num in num_l: 16 res = func(res, num) 17 return res 18 19 20 # print(reduce_test(lambda x, y: x * y, num_l)) 21 # reduce:处理一个序列,然后把序列合并操作 22 print(reduce(lambda x, y: x * y, num_l, 2)) 23 24 25 def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__ 26 """ 27 reduce(function, sequence[, initial]) -> value 28 29 Apply a function of two arguments cumulatively to the items of a sequence, 30 from left to right, so as to reduce the sequence to a single value. 31 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates 32 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items 33 of the sequence in the calculation, and serves as a default when the 34 sequence is empty. 35 """ 36 pass
4.其它内置
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 # import re 6 # some_text = 'a,b,,,,c d' 7 # reObj = re.compile('[, ]+') 创建re对象 8 # print(reObj.split(some_text)) 9 10 11 import re 12 13 some_text = 'a,b,,,,c d' 14 print(re.split('[, ]+', some_text)) # 会导致重复re模块,降低匹配速度 15 print(complex('1+2j')) 16 17 # print(complex('1 + 2j')) ValueError官方文档上 18 exec("print("hello, world")") 19 print(eval("1+2*2")) 20 a = '{"name":"alex"}' 21 print(eval(a)) 22 print(float(2)) 23 print(help(compile)) 24 print(repr(1)) # 终端打开 25 # slice() 切片 26 # vars() 有点像locals()