1 for in range ()
2 >>> L3 [0, 1, 4, 9,,, +, +, Bayi]4forin range (5 ) >>> g6 <generator object <genexpr> at 0x1022ef630>
List generation and generator generator, you can next() get the next return value of generator through a function. Generator saves the algorithm, each time it is called next(g) , computes g the value of the next element until it is calculated to the last element, no more elements are thrown when the StopIteration error occurs.
The correct way to get the content inside the iterator is through a for loop. and will not error.
for in range (ten)) for in G: ... Print (n) ... 0149162536496481
Generator is very powerful. If the calculated algorithm is more complex, and the loop with similar list generation for cannot be implemented, it can also be implemented with functions.
For example, the famous Fibonacci sequence (Fibonacci), except for the first and second numbers, can be summed up by the top two numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The Fibonacci sequence is not written in a list, but it is easy to print it out with a function:
1 deffib (max):2N, a, b = 0, 0, 13 whileN <Max:4 Print(b)5A, B = B, A +b6n = n + 17 return ' Done'8>>> FIB (10)91Ten1 One2 A3 -5 -8 the13 -21st -34 -55 +Done
The above functions and generator are only a step away. To turn a fib function into a generator, just print(b) change yield b it and define F=FIB (6), and F is a generator. Similarly, after changing a function to generator, we basically never use it next() to get the next return value, but instead iterate using the for loop directly. However, this method does not take the final return value of the function. If you want to get the return value, you must catch the StopIteration error, and the return value is included in StopIteration the value :
1>>> g = fib (6)2>>> whileTrue:3...Try:4... x =Next (g)5...Print('g:', X)6...exceptstopiteration as E:7...Print('Generator return value:', E.value)8... Break9 ...TenG:1 OneG:1 AG:2 -G:3 -G:5 theG:8 -GeneratorreturnValue:done
Here's the practice of writing code: You can also achieve the effect of concurrent operations in single-threaded situations by using yield:
1 #_*_coding:utf-8_*_2 __author__='Alex Li'3 4 Import Time5 defConsumer (name):6 Print("%s ready to eat buns!"%name)7 whileTrue:8Baozi =yield9 Ten Print("Bun [%s] came, eaten by [%s]!"%(baozi,name)) One A - defproducer (name): -c = Consumer ('A') theC2 = Consumer ('B') -C.__next__() -C2.__next__() - Print("Lao Tzu began to prepare steamed buns!") + forIinchRange (10): -Time.sleep (1) + Print("made 2 buns!") A c.send (i) at c2.send (i) - -Producer"Alex")
Concept part:
1. There are several types of data directly acting on A For loop: One is the collection data type, such as,,, list tuple dict set , str etc., and the second is generator , including yield the generator and the generator function with the band.
2.Iterable Iterative object: An object that can act directly on a for loop. isinstance()determines whether an object is an Iterable object
1>>> fromCollectionsImportiterable2>>>isinstance ([], iterable)3 True4>>>isinstance ({}, iterable)5 True6>>> Isinstance ('ABC', iterable)7 True8>>> Isinstance ((x forXinchRange (10) ), iterable)9 TrueTen>>> isinstance (100, iterable) OneFalse
3. Iterators Iterator :* objects that can be next() called by a function and constantly return the next value are called iterators. You can use to isinstance() determine whether an object is an Iterator object.
Transform: turn list , dict ,, and str so on Iterable Iterator to use the iter() function:
1 >>> isinstance (ITER ([]), Iterator)2True3 > >> Isinstance (ITER ('abc'), Iterator)4 True
Summary
Any object that can be used for for the loop is a Iterable type;
All objects that can be used for next() functions are Iterator types, which represent a sequence of lazy computations;
Collection data types such as list , dict ,, and str so on are Iterable not Iterator , however, you can iter() get an object from a function Iterator .
The Python for loop is essentially implemented by calling next() functions, such as:
forXinch[1, 2, 3, 4, 5]: Pass#equivalent to#first get the iterator object:it = iter ([1, 2, 3, 4, 5])#Loop: whileTrue:Try: #get the next value:x =Next (IT)exceptstopiteration:#exit the Loop if you encounter Stopiteration Break
Python base list generation, iterators