interpreter, you will find that a program has three tasks running in staggered motion, which looks like three tasks at the same time.Three, iteratorsWe already know that for there are several types of data that can be directly acting on a loop:A class is a collection of data types, such as,,, list tuple , and dict set str so on;One is generator to include the generator and yield the generator function with the band.These objects, which can be directly applied to for the loop, are called iterati
iteratorsA.__iter__A. __next__ = Next (a)print(res)Builder expressionList parsingA = ['jidan%s' for in range (10)]The generator expression is the result of the [] change to () of the list parsing.A1 = ('jidan%s' for in range (10))List parsing and builder expressions are a convenient way of programming, except that generator expressions are more memory-efficientPython uses an iterator protocol to make a for loop more general, and most built-in functions, which also use an iterator protocol to a
)) #Falseliter = l.__iter__ () print (' __next__ ' in Dir (Liter)) #Trueprint (liter.__next__ ()) #1print ( Liter.__next__ ()) #2print (liter.__next__ ()) #3print (liter.__next__ ()) #4 Method Two: Measure whether he is an iterator or an iterator:# method Two Tests whether he is an iterator or an iterator object L = [1,2,3]l_iter = l.__iter__ () from collections import Iterablefrom collections Import Iteratorprint ( Isinstance (l,iterable)) #Trueprint (Isinstance (l,itera
additional data Else :# If no exception occurs================================================================================For loopBased on the For loop, we can implement non-dependent index values1 dic={'a': 1,'b': 2,'c' : 3}2 for in dic:3 print( DIC[K]How the For Loop works1, executes the _ _iter_ _ () method of the in object to get an iterator object2, Execute _ _next_ _ method, assign a value variable to the resulting value, and then execute the Loop body code3, repeat procedure 2 un
Decorative Device
The essence is the function
function: Decorate other functions, that is, add additional functions for other functions
The principle that adorners need to follow:
Cannot modify the decorated function
Example: There are now three functions, each of which has its own function.If you need to add a log function to each of these three functions.Or these three functions are already running online, and now you need to add some more features. Possible
() function.(So the object that the generator can be called by the next () function and continually returns the next value is called an iterator) (it can be simply understood that the generator is an iterative object of iterators)All objects that can be used for a for loop are iterable types;All objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations;Learning examplesFunction representation 9*9 multiplication formula def Pro ():
:
12 34 56) 78 910
You can also use the next () function:List1 = [the] 910]it = ITER (list1) for Elenmet in It:print (Elenmet, end= "")Operation Result:
12 34 56) 78 910
GeneratorIn Python, a function that uses yield is called a generator (generator).Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.In the process of calling the genera
Iteration: It's about repeating things many times, using the __iter__ method, the iterator is the object with the next methodBuilt-in function iter can get iterators from objects that can be iteratedGet the sequence from the iterator:You can only use the throw exception in the If self.value>10, you cannot use break, or you will report a syntax errorGetting a sequence from an iterator I understand that it is to list the values that have been repeated before satisfying the condition.Generator:Expa
)List-Generated[x*x for x in range(1,11)]//把要生成的元素放在前面[x*x for x in range(1,11) if x%2 == 0]//for循环后面还可以加上if判断[m+n for m in ‘ABC‘ for n in ‘XYZ‘]//[‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]//可以使用两层循环,生成全排列三层以及三层以上就很少用Generator (Generator)List generation takes up a lot of space when the list size is largeSo the generator comes in handy, cycle through the calculation mechanismThe first method of defining generator, g = (x * x for x in range(10))for n in g: print(n)After you create a
memory space #迭代器并不会在内存中再占用一个大块内存, but with each time the loop generates one, each time next gives me a seven, generator 1, the essence of the generator is the iterator 2, the generator functiondef generator (): Print ('1') yield ' a ' =Generator ()print(ret)As long as the keyword function with yield is a generator function and yield is not shared with return and needs to be written inside the function#只要是生成器函数: After execution, a generator is given as the return value.def generator ()
cached. /png/www/example.com/public_html/cache/cache_;opcache.blacklist_filename=; The cache of large files is removed through the file size screen. By default, all files are cached.; o pcache.max_file_size=0; Check cache checksum once per N requests. The default value of 0 indicates that the check is disabled.; Due to the calculation of the checksum lossy performance, this directive should be tightly opened at the time of development debugging. O pcache.consistency_checks=0; When the cache is
results---------------A ready to eat buns! B 準備吃包子啦!老子开始準備做包子啦!做了1個包子分兩半!包子[0]来了,被[A]吃了!包子[0]来了,被[B]吃了!做了1個包子分兩半!包子[1]来了,被[A]吃了!包子[1]来了,被[B]吃了!做了1個包子分兩半! 包子[2]来了,被[A]吃了!包子[2]来了,被[B]吃了!做了1個包子分兩半!包子[3]来了,被[A]吃了!包子[3]来了,被[B]吃了!做了1個包子分兩半!包子[4]来了,被[A]吃了!包子[4]来了,被[B]吃了! 做了1個包子分兩半!包子[5]来了,被[A]吃了!包子[5]来了,被[B]吃了!做了1個包子分兩半!包子[6]来了,被[A]吃了!包子[6]来了,被[B]吃了!做了1個包子分兩半!包子[7]来了,被[A]吃了!包子[7] 来了,被[B]吃了!做了1個包子分兩半!包子[8]来了,被[A]吃了!包子[8]来了,被[B]吃了!做了1個包子分兩半!包子[9]来了,被[A]吃了!包子[9]来了,被[B]吃了! Process finished with exit code
() function, using Iterators with the next () functionS3 = Sentence (' Pig and Pepper ')it = ITER (S3)Print (IT) #Print (Next (IT)) #PigPrint (Next (IT)) #andPrint (Next (IT)) #Pepper#print (Next (IT)) #StopIterationAfter print (list (it)) #[] The end of the head, the iterator is uselessPrint (ITER (S3)) #[' Pig ', ' and ', ' Pepper '] to iterate again, to rebuild the iteratorThe #因为内置的 iter (...) function will do special processing of the sequence, so the 1th version of the sentence class can
default execution is done to the function, and if a return is encountered, the stopiteration terminating iteration is thrown directly.Code 5 File Readdef read_file (Fpath): block_size = 1024x768 with open (Fpath, ' RB ') as F: While True: BLOCK = F.read (block_ SIZE) if block: yield block else: returnCalling the Read () method directly on a file object causes unpredictable memory consumption. A good approach is
=show_2 () show_p.__next__() show_p.__next__() show_p.send (10)#incoming Ten# analog Range () def Lrange (m=0,n,l=1): count=m while Count N: yield Count + = L for in Lrange (2,10,2) :print(i)Asynchronous serialAdorner (decorator):Decorator principle:There are a few things you can do when @w1:1, execute W1 ()2, the modified function show passed to the W1 parameter3, the adorner must have a return value, return value in order to encapsulate the original show function into
method: Returns the next element of the iteratorA = {2,3,4,}b = iter (a) print (b.__next__ ()) print (b.__next__ ()) print (b.__next__ ()) print (b.__next__ ()) out : 234Traceback (most recent): File "practice3.py", line 216, in Ps: As can be seen from the above example, the elements in the iterator are accessed, and if you call the __next__ method again, you will be prompted stopiteration2) __iter__ method: Returns the Iterator object itselfA = {2,3,4,}b = iter (a) print (b.__iter__ ()) Out:
sequence to illustrate the difference between a generator and a normal function.Common function implementationdef fib (max): = 0, 0, 1 = [] while n Max: res.append (b) = B, a + b = n + 1 return= fib (6)print(res) for inch Res: Print (i) results of implementation [1, 1, 2, 3, 5, 8]138Generatordef fib2 (max): = 0, 0, 1 while n Max: yield b = b, A + b = n + 1
print
(res)
for in
Res:
print
print ("Welcome to Home Page ...") return "form home ..." @auth (Auth_type= "LDAP") def BBS (): Print ("Welcome to BBS Page") Index () Home () BBS () #函数没有, because there is no calling function, function calls inside the adorner, is the adorner called the function
Iterators and generators
Generator
With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list o
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.