编程方法:
函数式编程、面向过程、面向对象
高阶函数:满足俩个特性任意一个即为高阶函数
1.函数的传入参数是一个函数名
2.函数的返回值是一个函数名
#把函数当作参数传给另外一个函数 def foo(n): print(n) def bar(name): print('my name is %s' %name) # foo(bar) #函数的传入参数是一个函数名bar foo(bar('alex')) #返回值中包含函数 def bar(): print('from bar') def foo(): print('from foo') return bar n=foo() n() def hanle(): print('from hanle') return hanle h=hanle() h() def test1(): print('from test1') def test2(): print('from handle') return test1() #return 函数的返回结果
内置函数map、filter、reduce
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#内置函数map函数 num_l =[1,2,3,4,5,6] #lambda x:x+1 def add_one(x): return x+1 #lambda x:x-1 def reduce_one(x): return x-1 #lambda x:x**2 def pf(x): return x**2 def map_test(func,array): ret=[] for i in array: res=func(i) ret.append(res) return ret print(map_test(lambda x:x+1,num_l)) print('内置函数map,处理结果',map(lambda x:x+1,num_l)) msg='linhaifeng' print(list(map(lambda x:x.upper(),msg)))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#内置函数filter movie_people=['sb_alex','sb_wepeiqi','linhaifeng','sb_yuanhao'] def filter_test(array): ret=[] for p in array: if not p.startswith('sb'): ret.append(p) return ret print(filter_test(movie_people)) movie_people=['alex_sb','wepeiqi_sb','linhaifeng','yuanhao_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(filter_test(sb_show,movie_people)) #终极版本 movie_people=['alex_sb','wepeiqi_sb','linhaifeng','yuanhao_sb'] lambda n:n.endswith('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(filter_test(lambda n:n.endswith('sb'),movie_people)) #filter函数 print(filter(lambda n:n.endswith('sb'),movie_people)) print(list(filter(lambda n:not n.endswith('sb'),movie_people)))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#reduce num_l=[1,2,3,100] def reduce_test(array): res=0 for num in array: res+=num return res print(reduce_test(num_l)) #lambda x,y:x*y (整体把数据压缩成一个结果) def reduce_test(func,array,init=None): if init is None: res=array.pop(0) else: res=init for num in array: res=func(res,num) return res print(reduce_test(lambda x,y:x*y,num_l,100)) from functools import reduce print(reduce(lambda x,y:x*y,num_l,100))
总结:
map 处理序列中的每个元素,得到的结果是一个’列表‘,该“列表”元素个数及位置与原来一样
filter 遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来
reduce 处理一个序列,然后把序列进行合并操作
people=[ {'name':'alex','age':1000}, {'name':'wupeiqi','age':10000}, {'name':'yuanhao','age':9000}, {'name':'linhaifeng','age':18}, ] print(list(filter(lambda p:p['age']<=18,people)))
其他常用内置函数:
1.all():将序列中元素作布尔运算,若是空序列是True
2.any():与all()作用相反
3.bin():10进制转2进制
4.oct():10进制转8进制
5.hex():10进制转16进制
6.bool() 空、None、0的布尔值为False
7.bytes():将字符串转字节。ascii不能编码中文
name='你好' print(bytes(name,encoding='utf-8').decode('utf-8'))
8.chr():对应ascii转换为字符串
9.ord():对应ascii字符串转换成数字
print(chr(97)) print(ord('a'))
10.dir():某个对象下所有方法
11.divmod():取商得余数,分页用 。print(divmod(10,3))
12.eval():把字符串中的数据结构给提取出来
把字符串中的表达式做运算
13.hash():用于判断文件是否被人修改
可hash的数据类型即不可变数据类型,不可hash的数据类型即可变数据类型
14.help():打印方法
15.isinstance(1,int):判断1是否为int类型 isinstance('abc',str)判断‘abc’是否是str类型
16.zip((序列),(序列))序列:列表,元祖,字符串
print(list(zip(('a','n','c'),(1,2,3,4)))) p={'name':'alex','age':18,'gender':'none'} print(list(zip(p.keys(),p.values()))) print(list(zip(['a','b'],'12334')))
[('a', 1), ('n', 2), ('c', 3)]
[('name', 'alex'), ('age', 18), ('gender', 'none')]
[('a', '1'), ('b', '2')]
17.max/min 只要是for循环迭代即可
l1=['a10','b12','c10'] print(list(max(l1))) age_dic={'age1':18,'age4':20,'age3':100,'age2':30} print(max(age_dic.values())) print(max(age_dic)) #比较的是Key,但不知道是哪个key print(list(max(zip(age_dic.values(),age_dic.keys())))) #[100, 'age3'] people=[ {'name':'alex','age':100}, {'name':'wupeiqi','age':1000}, {'name':'yuanhao','age':900}, {'name':'linhaifeng','age':18}, ] print(max(people,key=lambda dic:dic['age'])) #{'name': 'wupeiqi', 'age': 1000} #相当于以下循环 ret=[] for item in people: ret.append(item['age']) print(ret) print(max(ret))
18.round():四舍五入
19.slice
l='hello' s1=slice(3,5) s2=slice(1,4,2) print(l[s1]) print(l[s2]) print(s2.start) print(s2.stop)
20.sorted
l=[3,2,31,'a',4] print(sorted(l)) #排序本质就是比较大小,不同类型不能比较 报错 people=[ {'name':'alex','age':100}, {'name':'wupeiqi','age':1000}, {'name':'yuanhao','age':900}, {'name':'linhaifeng','age':18}, ] print(sorted(people,key=lambda dic:dic['age']))