First, the agreement may iteration : iteration may be called to meet the requirements of the agreement can be iterative. The internal implementation of the method __iter__
iterable: iterable ------ corresponding mark
What is iteration? : A a value, like the value of a for loop
Strings, lists, tuples, sets, dictionaries are iterable
Second, the iterator protocol : the internal implementation of the __iter __, __ next__ method
Iterator most of them are inside the python to use, we are directly used on the line
Iterator advantage: If the iterator, save memory, easy to operate
dir ([1,2] .__ iter __ ()) is a list of all the methods implemented in iterator, and dir ([1,2]) is implemented in all the methods in the list, a list manner are returned to us, in order to facilitate a closer look, we have to convert them into a set, and then take the set difference, however, we see a list iterator more out of the three methods, then these three methods are doing it?
. 1 Print (the dir ([1,2] .__ ITER __ ())) # see a list of all the methods iterator 2 Print (the dir ([1,2])) # view a list of all the methods . 3 Print (SET (the dir ([ 1,2] .__ iter __ ()) ) - set (dir ([1,2])))
. 1 iter_l = [1,2,3,4,5,6] .__ ITER __ () 2 . 3 Print (iter_l .__ length_hint __ ()) # Get the length of the elements in the iterator . 4 # Print (iter_l .__ setState __ (. 4)) # the index specifies where to start the iteration . 5 . 6 Print (iter_l .__ Next __ ()) . 7 Print (iter_l .__ Next __ ()) . 8 Print (iter_l .__ Next __ ()) # a a values . 9 Print (Next (iter_l)) 10 #next (iter_l) this method and iter_l .__ next __ () method as recommended by next (iter_l) this
. 1 L = [1,2,3,4,5] 2 A = L .__ ITER __ () . 3 . 4 # Print (Next (A)) . 5 # Print (Next (A)) . 6 # Print (Next (A)) 7 # Print (the Next (a)) 8 # Print (the Next (a)) 9 # Print (the Next (a)) # the above list is only five lengths, while more than you print the error is reported. As the case of processing, the error will not 10 . 11 the while True: 12 is the try: 13 is Item Next __ .__ = A () 14 Print (Item) 15 the except the StopIteration: # Exception Handling 16 break
Third, the point may be the same iteration and iterator: can be used for loop
Fourth, can differences iterations and iterators: is more than internal iterator implements a method __next__
Five, and iterating iterative method:
The first: internal determination method is not realized __next__
. 1 '__iter__' in the dir (STR) # __iter__ inside If this method is to be iterative.
The second:
Iterable judgment is not iterables
Iterator judgment is not an iterator
usage:
. 1 from Collections Import the Iterable 2 from Collections Import the Iterator . 3 . 4 #, such as to a string . 5 S = 'ABC' . 6 Print (the isinstance (S, the Iterable)) determines the type of the isinstance # . 7 Print (the isinstance (S, the Iterator))
Analyzing range function and function map
1 map1=map(abs,[1,-2,3,-4]) 2 print(isinstance(map1,Iterable)) 3 print(isinstance(map1,Iterator))#map方法自带迭代器 4 5 s=range(100)#是一个可迭代的,但是不是迭代器 6 print(isinstance(s,Iterable)) 7 print(isinstance(s,Iterator))
五、生成器函数:常规定义函数,但是,使用yield语句而不是return语句返回结果。yield语句一次返回一个结果。生成器的好处,就是一下子不会在内存中生成太多的数据
python中提供的生成器:1.生成器函数 2.生成器表达式
生成器的本质:就是一个迭代器
1 def func(): #这是一个简单的函数 2 a=1 3 return a 4 print(func()) 5 6 7 def func(): 8 print('aaaaaaaaaaa') 9 a = 1 10 yield a # 返回第一个值 11 print('bbbbbb') 12 yield 12 # 返回第二个值 13 14 15 ret = func() # 得拿到一个生成器 16 # print(ret)#返回的是一个地址 17 print(next(ret))#取第一个值 18 print(next(ret))# 取第二个值 19 print(next(ret))# 取第三个值,会报错,因为没有yield第三个值 20 21
假如我想让工厂给学生做校服,生产2000000件衣服,我和工厂一说,工厂应该是先答应下来,然后再去生产,我可以一件一件的要,也可以根据学生一批一批的找工厂拿。
而不能是一说要生产2000000件衣服,工厂就先去做生产2000000件衣服,等回来做好了,学生都毕业了。。。
1 def make_cloth(): 2 for i in range(1,20000): 3 yield '第%s件衣服'%(i) 4 ret = make_cloth() 5 print(next(ret)) 6 print(next(ret)) 7 print(next(ret)) 8 for i in range(100): 9 print(next(ret)) 10 11
1 必须先用next再用send 2 def average(): 3 total=0 #总数 4 day=0 #天数 5 average=0 #平均数 6 while True: 7 day_num = yield average #average=0 8 total += day_num 9 day += 1 10 average = total/day 11 avg=average() #直接返回生成器 12 next(avg)#激活生成器,avg.send(),什么都不传的时候send和next的效果一样 13 print(avg.send(10)) 14 print(avg.send(20))#send 1.传值 2.next 15 print(avg.send(30)) 16 17
1 让装饰器去激活 2 def wrapper(func): 3 def inner(*args,**kwargs): 4 ret = func(*args,**kwargs) 5 next(ret) 6 return ret 7 return inner 8 9 @wrapper 10 def average(): 11 total=0 #总数 12 day=0 #天数 13 average=0 #平均数 14 while True: 15 day_num = yield average #average=0 16 total += day_num 17 day += 1 18 average = total/day 19 20 21 ret=average() #直接返回生成器 22 print(ret.send(10)) 23 print(ret.send(20))#send 1.传一个值过去 2.让当前yield继续执行 24 print(ret.send(30)) 25 26
1 import time 2 3 4 def tail(filename): 5 f = open(filename) 6 f.seek(0, 2) #从文件末尾算起 7 while True: 8 line = f.readline() # 读取文件中新的文本行 9 if not line: 10 time.sleep(0.1) 11 continue 12 yield line 13 14 tail_g = tail('tmp') 15 for line in tail_g: 16 print(line) 17 18
六、yield from
1 def func(): 2 # for i in 'AB': 3 # yield i 4 yield from 'AB' yield from 'AB'就相当于上面的for循环,吧循环简化了 5 yield from [1,2,3] 6 7 g=func() 8 print(list(g)) 9 # print(next(g)) 10 # print(next(g)) 11 12
七、列表推导式:
1 举例一 2 y=2 3 #for i in range(100): 4 # print(i*y) 5 6 7 #列表推导式是for循环的简写 8 l=[i*y for i in range(100)] 9 10 举例二 11 l=[{'name':'v1','age':'22'},{'name':'v2'}] 12 # for dic in l: 13 # print(dic['name']) 14 name_list=[dic['name'] for dic in l] 15 print(name_list) 16 17
1 # ======一层循环====== 2 l = [i*i for i in range(1,10)] 3 print(l) 4 # 上面的列表推倒式就相当于下面的 5 l = [] 6 for i in range(1,10): 7 l.append(i*i) 8 print(l) 9 l = [] 10 11 12 # ======多层循环======== 13 # 1.列表推倒式 14 l = [i*j for i in range(1,10) for j in range(1,10)] 15 print(l) 16 # 2.循环 17 l = [] 18 for i in range(1,10): 19 for j in range(1,10): 20 s = i*j 21 l.append(s) 22 print(l)
八、生成器表达式:类似于列表推倒式,就是把列表推导式的【】改为了()
1 l=[{'name':'v1','age':'22'},{'name':'v2'}] 2 3 name_list=(dic['name'] for dic in l)#吧列表生成器的[]改成() 4 print(name_list)#取出的是一个生成器,而不是要取得值,所以得加上next 5 print(next(name_list)) 6 print(next(name_list)) 7 # print(next(name_list)) 8 9
归类: Python相关