python in yield The key word is to distinguish between the old and the new Pythoner One of the symbols of .
yield It's a CET-6 word , The common meaning is “ yield , Yield ( Verb )”. there yield Probably interpreted as a strange meaning “ hand over ”. Under what circumstances should we , use yield Well ？ answer ： When dealing with large datasets .
yield It's hard to explain alone , But with next() In combination with , It's very simple . First look at a small chestnut :
a = [1, 2, 3] def y1(): for i in a: yield i b = y1() print(b) print(next(b)) print(next(b)) print(next(b))
Output is ：
<generator object y1 at 0x7f254434b6d8> 1 2 3
Let's use one yield Build a generator function y1,a It's the object we're going to traverse . Let's just print The return value of the generator , What you get is a memory address . We found that ,next(b) Run it every time ,yield The memory address pointed to will be moved backward in order . and next(b) The return value of is the data in the current address .yield+next It's just one. Sequential iterator .
Common as pytorch,keras etc. NN The basic class framework is used to process the data set yield+next To get batch data . What's the advantage of this , First, we can encapsulate the data entry into the form of an interface , Better modularity , And it doesn't let the data in main Function “ A presumptuous guest usurps the host's role ”. secondly , Preprocessing data and other work can be put into the generator part .