I. List-derived
1. The list derivation is a python-style notation. This is not only efficient, but also shorter.
in [all]: [ ' i:el , " i:el ", " i: El ]
Enumerate is a built-in function that allows the list to have "subscript" properties.
If you do not use a list deduction, the above example needs to be written
In []: LST = [" One"," Both","three"]in []: i =0In [26]: forEinchLST: ....: Lst[i]='%d:%s'%(I,lst[i]) .....: I+=1... ..: In [27]: lstout[27]: ['0:one','1:two','2:three']
Two. Generator (generator)
1. When to use the generator
In fact, you do not need a generator, only if it is required because of performance constraints, for example, you need to read a 10g txt file with Python, if you load the 10g file into memory processing (. Read () method), the memory must overflow. If you use generators here, you can cross-read and process, such as using (. ReadLine and. ReadLines), which can be processed at the same time as the loop reads, saving a lot of memory space.
(PS: If you write a read-write function to encapsulate to others to use, then consider the file capacity issues, you should consider using the generator.) )
2. Two ways to generate generators
2.1 The first one is relatively simple, the list derivation of the [] renamed () is OK
for in range (10))
2.2 The second option is to add the yield keyword to the function. Yield and return are a bit similar and can all be used to return a value, the difference is that yield encounters next () to return, and executes again from the last yield
statement returned.
3. How to tell if a function is a generator
The way to judge the generator is to look at its properties
in [+]: Dir (g) out[]: ['__class__'__next__ ' __repr__ ' __setattr__ ',]
Here you can see that G has a __next__ magic method, which is a unique property of the generator, the following two ways to call can be
in []: G.__next__(out[): 0In []: G.__next__() out[]: 1 in[ []: Next (g) out[44]: 4
Advanced features of Python 2: List derivation and generator