In Python, the more code is better, the less the better. The more complex the code is, the better, the simpler the better. Based on this idea, in Python, 1 lines of code can implement the function, the tactic does not write 5 lines. The less code, the higher the development efficiency 1. Sliced Slice (1) list, a tuple of operations that often take a specified index range, with loops is very cumbersome, so Python provides a slicing operator, can greatly simplify this operation (2) slice operation L[0:3] take the first three elements, starting from 0, take 3 but not 3, that is 0,1,2 L[1:2] 1, remove two elements l[-2:] start from the bottom 2nd, take the last l[-2:-1] from the bottom 2nd, take the countdown 1th, but not including the countdown 1th L[::5] From the beginning to the end, every 5 L[:10:2] Take the first 10, every two l[:] Copy a list (3) A tuple is also a list, the only difference is that a tuple is immutable, so a tuple can also be used for slicing, only Is the result of the operation is still a tuple (0,1,2,3,4,5) [: 3] Take the first three (0,1,2) (4) The string ' xxx ' can also be seen as a list, each element is a character. Therefore, the string can also be manipulated with a slice, but the result of the operation is still the string ' ABCDEFG ' [: 3] Take the first three ' ABC ' (5) with slicing operations, many places the loop is no longer needed. Python's slices are very flexible, and one line of code can implement many of the operations 2. Iteration (1) Given a list or tuple, we can traverse the list or tuple through a for loop, which I call Iteration (iteration) (2) in Python, where iterations are done through for...in, And many languages such as C or Jave, the iteration list is done by subscript (3) list this data type although there is subscript, but many other data types are not subscript, but as long as the object can be iterated, whether there is no subscript, can iterate, such as dict can iterate. Because dict are not stored in a list order, the resulting order of the iterations is likely to be different. By default, the sict iteration is key.
>>> d = {'a'b' 'C': 3 } for in D: ... Print (key) ... ACB
For value in D.values () # Iteration Value
For K, V in D.items () # Iterates both key and value
(4) Determine that an object is an iterative object, judged by the iterable type of the collections module:
from Import iterable>>> isinstance ('abc'# str can iterate True # Whether the list can iterate True# integer Whether it can iterate False
3. List comprehensions (1) list generation is a very simple but powerful build of Python built-in that can be used to create a list (2) If you want to generate [1x1, 2x2, 3x3, ..., 10x10], using the Loop method:
>>> L = [] for in range (1, one): ... . * x) ... >>> l[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
But the loop is too cumbersome, and the list generation can use a line of statements instead of loops to generate the list above:
for in range (1, one) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
(3) When writing the list generation, put the generated elements in front, followed by the For loop, you can also add if judgment, you can also use the two-layer loop
>>> [M + N forMinch 'ABC' forNinch 'XYZ']['AX','AY','AZ','BX',' by','BZ','CX','CY','CZ']
(4) Turn all the strings in a list into lowercase:
>>> L = ['Hello',' World','IBM','Apple']>>> [S.lower () forSinchL] ['Hello',' World','IBM','Apple']
(5) List generation can also use two variables to generate a list:
>>> d = {'x':'A','y':'B','Z':'C' }>>> [k +'='+ V forKvinchD.items ()] ['y=b','X=a','Z=c'](6) Exercise: If the list contains both a string and an integer, because the non-string type has no
lower()method, so the list generation will error, using the built-in isinstance function can be used to determine whether a variable is a string: isinstance (x, str) modified list generation, by adding if statement to ensure that the list generated by the correct execution
L1 = ['Hello'World'Apple' forif isinstance (S, str)]print(L2) # output: [' Hello ', ' world ', ' Apple ']
4. Generator (1) in Python, this side loop computes the mechanism, called the generator: Generator. (2) There are a number of ways to create a generator. The first method is simple, as long as a list-generated
[]Change into
(), a generator is created:
for in range () >>> 1, 4, 9, +, (+), +, +, Bayi]for in Range (Ten)>>> g<generator object <genexpr> at 0x1022ef630>
Create
LAnd
gThe only difference is the outermost one.
[]And
(),
Lis a list, and
gis a generator. can be done by
next()The function obtains the next return value of the generator (3) generator saves the algorithm, each call
next(g), we calculate the
gThe value of the next element, until it is calculated to the last element, when no more elements are thrown
StopIterationThe error. But constantly calling
next(g)It's so perverted, the right way is to use
forLoops, because generator is also an iterative object. So, after we create a generator, basically never call
next(), but through
forLoop to iterate over it, and no need to care
StopIterationThe error. (4) generator is very powerful. If the computed algorithm is more complex, a similar list-generated
forWhen the loop cannot be implemented, it can also be implemented with a function. For example, the famous Fibonacci sequence (Fibonacci), in addition to the first and second numbers, any number can be added by the first two numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The Fibonacci sequence is not written in a list, but it is easy to print it out with a function:
def fib (max): = 0, 0, 1 while n < Max: print(b) = B, A + b = n + 1
return'done'
Careful observation, you can see,
fibThe function is actually the extrapolation rule that defines the Fibonacci sequence, starting with the first element and extrapolating any subsequent elements, which are actually very similar to generator. In other words, the above functions and generator are only a step away. Want to put
fibfunction into generator, just put
print(b)Switch
yield bYou can do it:
def fib (max): = 0, 0, 1 while n < Max: yield b = b, A + b = n + 1
return'done'
This is another way to define generator. If a function definition contains
yieldkeyword, then this function is no longer a normal function, but a generator (5) generator and the execution process of the function is not the same. The function is executed sequentially, the return statement is encountered or the last line function statement is returned, and the function becomes generator, which executes at each call to next (), encounters a yield statement return, executes again from the last yield statement returned (6) Exercise: The Yang Hui triangle is defined as follows:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 each 5 Ten 5 1
Think of each line as a list, write a generator, and continuously output a list of the next line
deftriangles (): L= [1] whileTrue:yieldl l.append (0) L= [L[i-1] + l[i] forIinchRange (len (L))]n=0 forTinchtriangles ():Print(t) n= n + 1ifn = = 10: Break#Expected output:#[1]#[1, 1]#[1, 2, 1]#[1, 3, 3, 1]#[1, 4, 6, 4, 1]#[1, 5, ten, 5, 1]#[1, 6, 6, 1]#[1, 7, A, 7, 1]#[1, 8,---8, 1]#[1, 9, 126, 126, 9, 1]
5. iterators (1) can act directly on
forThere are several types of data in the loop: One is the collection data type, such as list, tuple, dict, set, str, etc., one is generator, including the generator and the generator with yield Function these objects that can directly act on a for loop are called an iterative object: Iterable can use Isinstance () to determine whether an object is a Iterable object
from Import iterable>>> isinstance ([], iterable) True>>> isinstance ({}, iterable) True >>> isinstance ('abc', iterable) True for in Range (), iterable) True>>> isinstance (iterable) False
(2) The generator can not only be used for a for loop, but can also be called by the next () function to return the next value until the last throw Stopiteration error indicates that the next value cannot continue to be returned. Can be called by the next () function and constantly return a worthy object called an iterator: Iterator (3) You can use Isinstance () to determine whether an object is a Iterator object:
from Import Iterator for in range (), Iterator) True>>> isinstance ([], Iterator) False>>> Isinstance ({}, Iterator) False>>> isinstance ('abc', Iterator) False
(4) Generators are Iterator objects, but list, tuple, str although iterable, but not Iterator (5) can use the ITER () function to the list, Dict, str and other iterable into Iterator:
>>> Isinstance (ITER ([]), Iterator) True>>> isinstance (iter ('ABC') ), Iterator) True
(6) All objects that can be used for a for loop are iterable types, (7) All objects that can be used for the next () function are iterator types, and they represent a sequence of lazy computations.
Python-Advanced Features