This article mainly introduces yield expression learning in python. there is a slightly strange expression in python called yieldexpression. This article will explore what this is, for more information, see yield expression, a slightly strange expression in python. Step by step.
Iterable
The code is as follows:
Mylist = [1, 2, 3]
For item in mylist:
Print str (item)
Mylist is a list. we can retrieve each item one by one. this process is called iteration. Like list, you can use "... In ..." Objects that are traversed in turn are called iterable. other iterable objects include string, tuple, and dict. One feature of iterable is that all items are stored in the memory, which leads to some inconveniences and disadvantages, and leads to generator (mentioned later ).
List comprehension (list derivation)
The code is as follows:
Mylist = [x * x for x in range (3)]
The right side of an expression is a short form of a for loop. it is enclosed in [] (called list comprehension). The expression value is a list. we can use for… as a normal list... In ..." Traverse its elements, such:
The code is as follows:
For item in mylist:
Print str (item)
Generator
Generator
Slightly modify the list comprehension:
The code is as follows:
Mygenerator = (x * x for x in range (3 ))
For item in mygenerator:
Print item
We can see that the expression is not a list, but a generator.
Generator also belongs to iterable, but its calling method is very special.
Yield
The code is as follows:
Def creatGenerator ():
Mylist = range (3)
For x in mylist:
Yield x * x
Mygenerator = creatGenerator ()
For x in mygenerator:
Print (x)
Yield uses the same method as return. But (the focus is on ):