Python's philosophy is: simple, elegant. As a result, many of the advanced features that are often used in Python are integrated to simplify the code.
For a list or tuple, take one of the elements, called slices (Slice).
L[start:end] Represents the element in L from the index number from start to end, where the index number range is 0~len (l)-1 if it is followed, and the index number range is -1~-len (l).
Python iterator for...in to complete. For list or tuple, this is the for name in names, and for Dict, which is for K, V in D.iteritems (), where K, V, respectively, represents key and value.
A simple list can be generated directly from the built-in function range ()
Range (start, end, step) The first parameter represents the starting value, the second parameter represents the end value plus one, the third value represents the step, and the default value is 1.
For complex lists, use the range Mate for...in and expressions to build, such as:
for in range (1, one) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
You can also add the following judgment:
for inch if x% 2 = = 0][4, 16, 36, 64, 100]
Depending on the expression, there are the following variants:
>>> d = {'x':'A','y':'B','Z':'C' }>>> [k +'='-0 forKvinchD.iteritems ()] ['y=b','X=a','Z=c']
>>> L = ['Hello',' World','IBM','Apple']>>> [S.lower () forSinchL] ['Hello',' World','IBM','Apple']
Generating a list directly consumes a lot of memory, and the generator calculates each value in turn based on an algorithm.
There are two ways to create a generator, and the first one is to change [] to (), such as:
for in range () >>> 1, 4, 9, +, (+), +, +, Bayi]for in Range (Ten)>>> g<generator object <genexpr> at 0x104feab40>
Use the next () method when calling:
>>> G.next () 0 >>> G.next ( ) 1>>> G.next () 4>>> G.next () 9>>> G.next () 16>>> G.next () 25>>> G.next () 36> >> G.next () 49>>> G.next () 64>>> G.next () 81>>> G.next () Traceback (most recent): File <stdin> , Line 1, in < Module>stopiteration
After the calculation is finished, the call will throw stopiteration error. Alternatively, you can iterate over the output with for...in.
The second is to replace the return of the created function with yield.
def fib (max): = 0, 0, 1 while n < Max: yield b = b, A + b = n + 1
Generator executes at the time of each invocation next()
, encounters a yield
statement return, and resumes execution from the last yield
statement returned.
>>>defOdd (): ...Print 'Step 1'... yield1... Print 'Step 2'... yield3... Print 'Step 3'... yield5...>>> o =Odd ()>>>o.next () step11>>>o.next () step23>>>o.next () step35>>>O.next () Traceback (most recent): File"<stdin>", Line 1,inch<module>stopiteration
DAY-5: Python Advanced Features