1. List-generation (comprehensions)
In Python, list generation is used to create lists, compared to using loops to make them more concise. For example, generate [1*1, 2*2, ..., 10*10], loop with three lines:
1 L = []2 for in range (1,11):3 l.append (i*i)
The list generation is only one row, preceded by the build rule, followed by the initial element, and finally the criteria can be added:
1 for in range (1, 11)]
List generation can also be implemented in multi-layered loops, as well as judging, just the chestnut and then write a little more complicated:
for inch for inch if a==b]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2. Generator (Generator)
List-generated list elements are limited because the list is stored in memory after all, and the generator does not need to worry about memory issues. Because the generator is saving the algorithm, compared to the list generation, the generator is time-changing space.
The generator is created in two ways:
2.1 Replace the list-generated [] with ():
1 for in range2 >>> g3 <generator object <genexpr> at 0x104feab40>4 >>> g.next ()506 >>> G.next () #遍历也可以使用for循环, without more elements, throws stopiteration error. 7 1
2.2 Using the function implementation, only need to turn the return statement into yield, in addition to the generator is the yield statement after execution stop, call the next to continue execution.
1 def fib (max): 2 N, a, b = 0, 0, 13 while n < Max:4 yield b5
A, B = B, A + b6 n = n + 1
Python Learning notes-list generation and builder