迭代器
1 迭代器:迭代的工具 2 1.什么是迭代:指的是一个重复的过程,每次重复称为一次迭代,并且每次重复的结果是下一次重复的初始值 3 例: 4 while True: 5 print('====>'') 6 7 l=['a','b','c'] 8 count=0 9 while count<len(l): 10 print(l[count]) 11 count+=1 12 13 2.为什么要有迭代器? 14 对于序列类型:str,list,tuple,可以依赖索引来迭代取值, 15 但是对于dict,set,文件,python必须为我们提供一种不依赖于索引的迭代取值的方式-》迭代器 16 17 3.可迭代的对象(下列 都是):obj.__iter__ 18 name='egon' 19 l=[1,2,3] 20 t=(1,2,3) 21 d=['name':'egon','age':18,'sex':'male'] 22 s={'a','b','c'} 23 f=open('a.txt','w',encoding='utf-8') 24 25 name.__iter__ 26 l.__iter__ 27 t.__iter__ 28 d.__iter__ 29 s.__iter__ 30 f.__iter__ 31 32 4.迭代器对象(只有文件是):obj.__iter__,obj.__next__ 33 f.__iter__ 34 f.__next__ 35 36 总结: 37 1.可迭代对象不一定是迭代器的对象 38 2.迭代器对象一定是可迭代器的对象 39 3.调用obj.__iter__()方法,可迭代对象调用iter就转换成了迭代器对象,文件直接是迭代器对象(对于迭代器对象,执行__iter__得到的仍然是它本身) 40 41 这个例子说明文件执行iter还是迭代器对象,返回值为True 42 f=open('a.txt','w',encoding='utf-8') 43 f_iter=f.__iter__().__iter__().__iter__().__iter__() 44 print(f_iter is f) 45 46 d={'name':'egon','age':18,'sex':'male'} 47 d_iter=d.__iter__() 48 print(d_iter.__next__()) 49 print(d_iter.__next__()) 50 print(d_iter.__next__()) 51 print(d_iter.__next__()) #迭代器d_iter没有值了,就会抛出异常StopIteration 52 53 54 f=open('a.txt','w',encoding='utf-8') 55 f_iter=f.__iter__().__iter__().__iter__().__iter__() 56 57 f=open('F:python20期sa.txt','r',encoding='utf-8') 58 print(f.__next__()) 59 print(f.__next__()) 60 print(f.__next__()) 61 print(f.__next__()) 62 f.close() 63 64 l=['a','b','c'] 65 l_iter=l.__iter__() 66 print(l_iter.__next__()) 67 print(l_iter.__next__()) 68 print(l_iter.__next__()) 69 70 d={'name':'egon','age':18,'sex':'male'} 71 d_iter=iter(d) #就相当于d_iter=d.__iter__()和len(obj)=obj__iter__() 72 73 74 d={'name':'egon','age':18,'sex':'male'} 75 d_iter=iter(d) #就相当于d_iter=d.__iter__ 76 while True:#加上这个是为了取消StopIteration报错 77 try:#意思是监测这段代码的行为print(next(d_iter)),如果有异常就判断异常是不是StopIteration:,如果是就break 78 print(next(d_iter)) 79 except StopIteration: 80 break 81 print('====>') 82 print('====>') 83 print('====>') 84 print('====>') 85 86 d={'name':'egon','age':18,'sex':'male'} 87 for k in d: 88 print(k) 89 print('====>') 90 print('====>') 91 print('====>') 92 print('====>') 93 94 for循环总结详解(上为实例): 95 1.调用in后面的obj_iter=obj.__iter__() 96 2.k=obj_iter.__next__() 97 3.捕捉到StopIteration异常,结束迭代 98 99 100 101 102 #总结迭代器的优缺点: 103 #优点: 104 #1、提供一种统一的、不依赖于索引的取值方式,为for循环的实现提供了依据 105 #2、迭代器同一时间在内存中只有一个值——》更节省内存, 106 107 #缺点: 108 #1、只能往后取,并且是一次性的 109 #2、不能统计值的个数,即长度
生成器
1 生成器:只有在函数体内出现yield关键字,那么再执行函数就不会执行函数代码,会得到一个结果,该结果就是生成器 2 3 def func(): 4 print('=====>1') 5 yield 1 6 print('=====>2') 7 yield 2 8 print('=====>3') 9 yield 3 10 11 #生成器就是迭代器 12 # g=func() 13 ##g.__iter__和g.__next__都有,所以说生成器就是迭代器 14 # 15 #next(g)#返回值是======>1 16 # 17 #res1=next(g) 18 # print(res1) 19 # 20 # 21 # res2=next(g) 22 # print(res2) 23 # 24 # 25 # res3=next(g) 26 # print(res3) 27 #yield的功能: 28 #1、yield为我们提供了一种自定义迭代器对象的方法 29 #2、yield与return的区别1:yield可以返回多次值 #2:函数暂停与再继续的状态是由yield帮我们保存的 30 31 obj=range(1,1000000000000000000000000000000000000000000000000000000000000000,2) 32 obj_iter=obj.__iter__() 33 print(next(obj_iter)) 34 print(next(obj_iter)) 35 print(next(obj_iter)) 36 print(next(obj_iter)) 37 print(next(obj_iter)) 38 39 def my_range(start,stop,step=1):#step步长默认为一 40 while start < stop: 41 yield start #start=1 42 start+=step #start=3 43 44 45 g=my_range(1,5,2) 46 print(g) 47 48 print(next(g)) 49 print(next(g)) 50 print(next(g)) 51 print(next(g)) 52 print(next(g)) 53 print(next(g)) 54 print(next(g)) 55 for i in my_range(1,5,2): 56 print(i) 57 58 小练习::tail -f access.log | grep '404' 59 import time 60 def tail(filepath):#文件路径 61 with open(filepath,'rb') as f:#把光标放到最后 62 f.seek(0,2)#直接跑到文件末尾去了 63 while True:#循环去读 64 line=f.readline()#读一行 65 if line:#如果有值 66 yield line#把这个值返回,让这个值持续运行 67 else:#如果没有值 68 time.sleep(0.05) 69 70 def grep(lines,pattern):#lines,pattern是匹配的东西 71 for line in lines: 72 line=line.decode('utf-8')#把数字转成字符串类型 73 if pattern in line: 74 yield line#只干过滤的活 75 76 77 lines=grep(tail('access.log'),'404') 78 79 for line in lines: 80 print(line) 81 82 83 #了解知识点:yield表达式形式的用法 84 def eater(name): 85 print('%s ready to eat' %name) 86 food_list=[]#加一个列表 87 while True: 88 food=yield food_list#food=yield='一盆骨头'#只要写成yield就是生成器了, 89 food_list.append(food) 90 print('%s start to eat %s' %(name,food)) 91 92 93 e=eater('alex') 94 95 #首先初始化:#初始化一次就是next(e) 96 print(e.send(None)) # 等同于next(e) 97 #然后e.send:1 从暂停的位置将值传给yield,在用yield给前面的变量 2、与(就是next操作)next一样 98 print(e.send('一桶泔水')) 99 print(e.send('一盆骨头'))
面向编程
三元表达式
1 def my_max(x,y): 2 if x >= y: 3 return x 4 else: 5 return y 6 7 x=10 8 y=20 9 10 # res=x if x >= y else y 11 # print(res) 12 13 name=input('>>: ').strip() 14 15 res='Sb' if name == 'alex' else 'NB' 16 print(res)
列表推导式和生成器表达式
1 #1 列表推导式 2 # l=[] 3 # for i in range(1,11): 4 # res='egg'+str(i) 5 # l.append(res) 6 # 7 # print(l) 8 9 # l=['egg'+str(i) for i in range(1,11)] 10 # print(l) 11 12 # l1=['egg'+str(i) for i in range(1,11) if i >= 6] 13 # print(l1) 14 15 # l1=[] 16 # for i in range(1,11): 17 # if i >= 6: 18 # l1.append('egg'+str(i)) 19 # 20 21 #2 生成器表达式 22 23 # g=('egg'+str(i) for i in range(0,1000000000000000000000000000000000)) 24 # print(g) 25 # print(next(g)) 26 # print(next(g)) 27 # print(next(g)) 28 29 30 #练习 31 names=['egon','alex_sb','wupeiqi','yuanhao'] 32 33 # names=[name.upper() for name in names] 34 # print(names) 35 36 # sbs=[name for name in names if name.endswith('sb')] 37 # print(sbs) 38 39 40 # obj=list('abcdef') 41 # print(obj) 42 43 # print(max([1,2,3,4,5])) 44 45 # g=(i for i in range(10)) 46 # print(max(g)) 47 # 48 # print(max(g)) 49 50 with open('a.txt','r',encoding='utf-8') as f: 51 # l=[] 52 # for line in f: 53 # # print(len(line)) 54 # l.append(len(line)) 55 56 # g=(len(line) for line in f) 57 # res=max(g) 58 # print(res) 59 60 # print(max(len(line) for line in f)) 61 62 print(sum(len(line) for line in f))
递归调用
1 #递归调用:在调用一个函数的过程中,直接或者间接又调用该函数本身,称之为递归调用 2 #递归必备的两个阶段:1、递推 2、回溯 3 4 # import sys 5 # print(sys.getrecursionlimit()) 6 # sys.setrecursionlimit(2000) 7 # print(sys.getrecursionlimit()) 8 9 # def func(n): 10 # print('---->',n) 11 # func(n+1) 12 # 13 # func(0) 14 15 16 # def bar(): 17 # print('from bar') 18 # func() 19 # 20 # def func(): 21 # print('from func') 22 # bar() 23 # 24 # func() 25 26 27 # age(5) = age(4) + 2 28 # age(4) = age(3) + 2 29 # age(3) = age(2) + 2 30 # age(2) = age(1) + 2 31 # 32 # age(1) = 18 33 34 # age(n)=age(n-1)+2 # n > 1 35 # age(1) = 18 #n = 1 36 37 38 # def age(n): 39 # if n == 1: 40 # return 18 41 # return age(n-1) + 2 42 # 43 # res=age(5) 44 # print(res) 45 46 47 # l=[1,[2,[3,[4,[5,[6,[7,]]]]]]] 48 # 49 # 50 # def func(l): 51 # for item in l: 52 # if type(item) is list: 53 # func(item) 54 # else: 55 # print(item) 56 57 58 59 # def func(): 60 # print('===>') 61 # func() 62 # 63 # func()
二分法
1 #了解的知识点 2 l=[1,2,10,30,33,99,101,200,301,402] #从小到大排列的数字列表 3 4 def binary_search(l,num): 5 print(l) 6 if len(l) == 0: 7 print('not exists') 8 return 9 mid_index=len(l) // 2 10 if num > l[mid_index]: 11 #往右找 12 binary_search(l[mid_index+1:],num) 13 14 elif num < l[mid_index]: 15 #往左找 16 binary_search(l[0:mid_index],num) 17 else: 18 print('find it') 19 20 # binary_search(l,301) 21 binary_search(l,302)
匿名函数
1 # def func(): #func=内存地址 2 # print('from func') 3 # 4 # func() 5 # func() 6 7 8 # 内存地址 9 # def my_sum(x,y): 10 # return x+y 11 12 # print(lambda x,y:x+y) 13 # print((lambda x,y:x+y)(1,2)) 14 15 # func=lambda x,y:x+y 16 # # print(func) 17 # print(func(1,2)) 18 19 20 #max,min,sorted,map,reduce,filter 21 # salaries={ 22 # 'egon':3000, 23 # 'alex':100000000, 24 # 'wupeiqi':10000, 25 # 'yuanhao':2000 26 # } 27 # print(max(salaries)) 28 29 # s='hello' 30 # l=[1,2,3] 31 # g=zip(s,l) 32 # # print(g) 33 # print(list(g)) 34 35 # g=zip(salaries.values(),salaries.keys()) 36 # # print(list(g)) 37 # print(max(g)) 38 39 # def func(k): 40 # return salaries[k] 41 42 # print(max(salaries,key=func)) #key=func('egon') 43 44 # print(max(salaries,key=lambda k:salaries[k])) #key=func('egon') 45 # print(min(salaries,key=lambda k:salaries[k])) #key=func('egon') 46 47 48 49 50 51 52 #sorted 53 # salaries={ 54 # 'egon':3000, 55 # 'alex':100000000, 56 # 'wupeiqi':10000, 57 # 'yuanhao':2000 58 # } 59 # print(sorted(salaries,key=lambda k:salaries[k])) 60 # print(sorted(salaries,key=lambda k:salaries[k],reverse=True)) 61 62 63 #map,reduce,filter 64 # names=['alex','wupeiqi','yuanhao'] 65 # l=[] 66 # for name in names: 67 # res='%s_SB' %name 68 # l.append(res) 69 # 70 # print(l) 71 72 # g=map(lambda name:'%s_SB' %name,names) 73 # # print(g) 74 # print(list(g)) 75 76 77 # names=['alex_sb','wupeiqi_sb','yuanhao_sb','egon'] 78 # g=filter(lambda x:x.endswith('sb'),names) 79 # print(g) 80 # print(list(g)) 81 82 83 84 from functools import reduce 85 print(reduce(lambda x,y:x+y,range(1,101),100))
内置函数
1 #了解 2 # print(abs(-1)) 3 4 # print(all([1,'a','b',0])) 5 # print(all([])) 6 7 # print(any([None,False,0,1])) 8 # print(any([])) 9 10 11 # print(bin(11)) 12 # print(hex(11)) 13 # print(oct(11)) 14 15 # print('xxx'.encode('utf-8')) 16 # print(bytes('xxx',encoding='utf-8')) 17 18 # print(callable(max)) 19 20 # print(chr(65)) 21 # # print(chr(90)) 22 # # print(chr(39)) 23 # print(ord('A')) 24 # print(ord('@')) 25 26 27 # import os 28 # print(dir(os)) 29 30 31 # s=set({1,2,3}) 32 # s.add(4) 33 # print(s) 34 35 # s=frozenset({1,2,3}) #不可变集合 36 37 # print(hash('xxx')) 38 39 # l=[1,2,'a',4] 40 # print(list(reversed(l))) 41 42 43 # s=slice(1,5,2) 44 # l=['a','b','c','d','e'] 45 # 46 # # print(l[1:5:2]) 47 # # print(l[1:5:2]) 48 # 49 # print(l[s]) 50 51 52 # print(vars() is locals()) 53 54 55 #面向对象 56 classmethod 57 staticmethod 58 property 59 60 61 hasattr 62 getattr 63 setattr 64 delattr 65 66 isinstance 67 issubclass 68 69 object 70 71 super 72 73 # obj.__dict__() #vars(obj) 74 75 #__import__ 76 # choice=input('>>: ') 77 # print(choice,type(choice)) 78 # 79 # # import 'time' 80 # m=__import__(choice) 81 # m.sleep(10) 82 83 84 85 #掌握: 86 #divmod 87 # print(divmod(10011,25)) 88 89 90 #enumerate 91 # l=['a','b','c'] 92 93 # for i in l: 94 # print(l.index(i),i,) 95 96 # for i,v in enumerate(l): 97 # print(i,v) 98 99 #eval: 100 # res=eval('[1,2,3]') 101 # print(res,type(res)) 102 103 # res=exec('[1,2,3]') 104 # print(res) 105 106 #pow 107 # res=pow(2,3,3) # (2 ** 3 )%3 108 # print(res) 109 110 #round 111 # print(round(3.5))