A slightly odd expression in Python is called yield expression, and this article explores what it is. One step at a step.
Iterable
Copy Code code as follows:
MyList = [1,2,3]
For item in MyList:
Print str (item)
MyList is a list, we can take out each item, this process is called iteration. Like List this can use "for...in ..." in order to traverse the object is called Iterable, the other iterable also have string, tuple, dict and so on. One of the features of Iterable is that all of the item is stored in memory, which can cause some inconvenience and disadvantage, thus creating a generator (described later).
List comprehension (matrix derivation)
Copy Code code as follows:
MyList = [x*x for x in range (3)]
The right-hand side of the expression is a short form for the loop, wrapped in [] (called list comprehension), and the value of the expression is a list, and we can use "for...in ..." like the normal list to iterate through its elements, such as:
Copy Code code as follows:
For item in MyList:
Print str (item)
Generator
Generator
Make a slight change to the list comprehension above:
Copy Code code as follows:
Mygenerator = (x*x for x in range (3))
For item in Mygenerator:
Print Item
You can see that the [] is replaced by (), the value of the expression is no longer a list, but a generator.
Generator also belongs to Iterable, but the way it is called is very special.
Yield
Copy Code code as follows:
Def creatgenerator ():
MyList = Range (3)
For x in MyList:
Yield x*x
Mygenerator = Creatgenerator ()
For x in Mygenerator:
Print (x)
The use of yield is the same as return. But (the emphasis):