Python Review points

Source: Internet
Author: User
Tags abs closure function definition generator iterable in python

Python Practical case

basic knowledge of Python

All the contents of this article are notes made during the study period, only for personal inspection and review convenience and record. All content is excerpted from: http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000 data type integer floating-point number

String if the string contains both ' and contains ', it can be escaped with escape character \. A multiline string can be represented by the ' string content ' to represent the inner string of R ' representations ' by default not to escape the Boolean value, True, false; Boolean values can be null with and, OR and not, None, and variable names must be a combination of uppercase and lowercase, numbers, and _. and cannot start with a number

constants, all uppercase variable names represent constants

A division is//, called a floor divide, the division of two integers is still an integer

>>>/3
3
the difference between list and tuple (tuples)

List definition, classmates = [' Michael ', ' Bob ', ' Tracy ']

Tuple definition, classmates = (' Michael ', ' Bob ', ' Tracy ') list variable, tuple unchanged. list is defined with [] and tuple (). Can be obtained by means of positive integers and negative numbers.

Tuple's so-called "invariant" is to say that each element of tuple, ' points never change '. Point to ' a ', can not be changed to point ' B ', point to a list, can not be changed to point to other objects, but the list itself is variable.
Conditional Judgment
If < condition judgment 1>:
    < execution 1>
elif < conditional judgment 2>:
    < execution 2> Elif
< conditional judgment 3>:
    < execution 3>
Else:
    < executive 4>

Pay attention to the conditions behind: don't write less. Loops

For...in cycle

names = [' Michael ', ' Bob ', ' Tracy '] for
name in names:
print (name)
Range () function, you can generate an integer sequence, and then through the list () function can be converted to list

While loop

sum = 0
n =% while
n > 0:
sum = sum + N
n = n-2
print (sum)
Dict and set

Dict: Dictionary, similar to map, repeatable, quick lookup.

>>> d = {' Michael ': ' Bob ': $, ' Tracy ':}
>>> d[' Michael ']
95

Compared with list, Dict has the following characteristics: Find and insert the speed is very fast, not with the increase of key and slow, need to occupy a lot of memory, memory waste much.

The list is the opposite: the time to find and insert increases as the element increases;

So, Dict is a way of exchanging space for time.

Set: Collection, not repeatable. To create a set, you need to provide a list as an input collection

>>> s = Set ([1, 2, 3])
>>> s
{1, 2, 3}
function Defining Functions

Define a function to use the DEF statement, in turn, write the function name, parentheses, arguments in parentheses, and colons:, and then, in the indented block, write the function body, and the return value of the function is returned with the returns statement.

def my_abs (x):
    if x >= 0: Return
        x
    else:
        return-x

Notice that when the statement inside the function body executes, once the return is executed, the function executes and returns the result. Therefore, a very complex logic can be achieved within a function through conditional judgments and loops.

If there is no return statement, the function completes after execution and returns the result, except that the result is none.

Return none can be abbreviated to return.

Empty function

Def NOP (): Pass
Pass statement does nothing,

Parameter checking
Data type checking can be implemented with built-in functions isinstance ()

def my_abs (x):
If not isinstance (x, (int, float):
    raise TypeError (' bad operand type ')
if x >= 0:
    R Eturn x
Else:
    return-x

* * Returns multiple values * *

For example, in the game often need to move from one point to another point, given the coordinates, displacements and angles, you can calculate the new coordinates:

Import Math

def move (x, y, step, angle=0):
    NX = x + step * math.cos (angle)
    NY = y-step * Math.sin (angle) 
  
   return NX, NY
  
The return value is actually a tuple. However, in syntax, returning a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, by position to the corresponding value, so Python's function to return a multi-valued is actually to return a tuple, but it is more convenient to write. Summary

When defining functions, you need to determine the number of function names and parameters;

If necessary, you can check the data type of the parameter first;

The function body can return the function result at any time.

Automatically return none when the function completes and no return statement is performed.

A function can return multiple values at the same time, but it is actually a tuple. function Arguments

Default parameters

def power (x, n=2):
s = 1 while
n > 0:
    n = n-1
    s = S * x return
S

When setting the default parameters, there are a few points to note: First, the required parameters are preceded by the default parameters, otherwise the Python interpreter will complain (think about why the default parameters cannot be placed before the required arguments) and how to set the default parameters.
When a function has more than one parameter, the parameter that is changed is placed in front, and the small variable is put behind. Parameters that vary little can be used as default parameters.
What is the benefit of using default parameters. The biggest advantage is that it can reduce the difficulty of calling a function.

* * Define default parameters Keep in mind: The default argument must point to the invariant object. If it is a list, you can use L=none to declare * * variable parameters
Add a * number in front of the parameter.

Defined:

Def calc (*numbers):
    sum = 0 for
    n in numbers:
        sum = SUM + N * n * return
    sum

Call Mode 1:

>>> Calc (1, 2)
5
>>> calc ()
0

Call Mode 2: You can pass the list or the tuple element into a variable parameter by adding a * number in front of the list or tuple.

>>> nums = [1, 2, 3]
>>> calc (*nums)
14

Keyword parameters
Set at:

def person (name, age, **kw):
print (' name: ', Name, ' Age: ', age, ' other: ', kw)

Call Mode 1:

>>> person (' Michael, "
Name:michael age:30 other: {}

Call Mode 2:

>>> person (' Bob ', city= ' Beijing ')
name:bob age:35 Other: {' City ': ' Beijing '}
>>> Person (' Adam ', "gender= ' m ', job= ' Engineer ')
Name:adam age:45 Other: {' Gender ': ' m ', ' job ': ' Engineer '}

Call Mode 3:

>>> extra = {' City ': ' Beijing ', ' job ': ' Engineer '}
>>> person (' Jack ', **extra)
Name:jack A Ge:24: {' City ': ' Beijing ', ' job ': ' Engineer '}

Named keyword parameter
How to define:

def person (name, age, *args, City, Job):
print (name, age, args, city, job)

Or

def person (name, age, *, city= ' Beijing ', job):
print (name, age, city, job)

Call Mode:

>>> person (' Jack ', job= ' Engineer ')
Jack Beijing Engineer
It is important to note that if you do not have variable parameters, you must add one as a special separator. If missing, the Python interpreter will not recognize positional parameters and named keyword parameters

The Python function has a very flexible parameter shape that enables both simple calls and very complex parameters to be passed in. The default parameter must be an immutable object, and if it is a mutable object, the program will run with a logical error. Note The syntax for defining variable parameters and keyword parameters: *args is a variable parameter, args receives a tuple; **kw is the keyword parameter, and kw receives a dict. And how to pass the syntax of a variable parameter and keyword parameter when calling a function: variable parameters can be passed directly into: Func (1, 2, 3), can be assembled first list or tuple, and then passed through the *args: Func (* (1, 2, 3); Keyword parameters can be passed directly to: func ( A=1, b=2), you can assemble the dict first, and then pass **kw to: func (**{' a ': 1, ' B ': 2}). Using *args and **kw is a Python idiom, and of course you can use other parameter names, but it's best to use idiomatic usage. Named keyword parameters are designed to limit the number of parameter names that callers can pass in, and can provide default values. Define a named keyword parameter do not forget to write the separator when there is no variable parameter, otherwise the location parameter will be defined. Advanced Features slices

Taking part of a list or tuple is a very common operation
Take the top three of the list:

>>> L = [' Michael ', ' Sarah ', ' Tracy ', ' Bob ', ' Jack ']
>>> l[0:3]
[' Michael ', ' Sarah ', ' Tracy ']

If the first index is 0, it can also be omitted, such as L[:3].

Support Countdown slices

>>> L = List (range ())
>>> L
[0, 1, 2, 3, ..., 99]

First 10 number, each two takes one:

>>> L[:10:2]
[0, 2, 4, 6, 8]

All numbers, every 5 to one:

>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

Even write nothing, write only [:] You can copy a list as is:

>>> l[:]
[0, 1, 2, 3, ..., 99]

* * Tuple and strings can also be similarly manipulated * * iterations

In Python, iterations are done through the for ... in

As long as it is an iterative object, whether or not subscript, can be iterative, such as dict can iterate:

>>> d = {' A ': 1, ' B ': 2, ' C ': 3}
>>> for key in D: ...     Print (key) ...
A
c
b

Dict stores are not listed in the order of the list, so the order of results for iterations is likely to be different.

By default, the Dict iteration is the key. If you want to iterate over value, you can use the for value in D.values (), and if you want to iterate both key and value, you can use for K, V in D.items ().

How can you tell if an object is an iterative object?
Judged by the iterable type of the collections module:

>>> from collections import iterable
>>> isinstance (' abc ', iterable) # str can iterate
True
>>> isinstance ([1,2,3], iterable) # list can iterate
True
>>> isinstance (123, iterable) # integers can be iterated
False

What if you want to implement a subscript loop like Java for the list? Python's built-in enumerate function can turn a list into an index-element pair so that the index and the elements themselves can be iterated in the for loop at the same time:

>>> for I, value in enumerate ([' A ', ' B ', ' C ']):
...     Print (i, value)
...
0 A
1 B
2 C
List-generated

The list-generation, comprehensions, is a very simple, powerful build that Python can use to create a list.

For example, to generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] You can use List (range (1, 11)):

>>> list (range (1, one))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If you want to generate [1x1, 2x2, 3x3, ..., 10x10], you can do this:

>>> [x * x for x in range (1, one)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Build Device

Creating a list of 1 million elements, not only takes up a lot of storage space, but if we only need to access the first few elements, the space behind most of the elements is wasted. The mechanism of computation on one side of the loop, called the generator: Generator. Generator saves the algorithm by calling next (g) to compute the value of the next element of G until the last element is computed, and no more elements are thrown when the stopiteration error is raised. The first method of creating a method is simple, as long as you change a list-generated [] to (), you create a generator:

>>> L = [x * x for x in range (Ten)]
>>> L
[0, 1, 4, 9,,, BA]
>>> g = (x * x for x in range (a))
>>> g
<generator object <genexpr> at 0x1022ef630>
Another way to define generator. If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator:
def fib (max):
    N, a, b = 0, 0, 1 while
    n < max:
        yield b
        A, B = B, a + b
        n = n + 1 return
    ' done '
The difference between generator and functions
Http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014317799226173f45ce40636141b6abc8424e12b5fb27000

Most difficult to understand is that the generator and function of the execution process is not the same. The function is executed sequentially, and the return statement is encountered or the last line of function statement is returned. The function that becomes generator, executes at each call next (), encounters a yield statement return, and executes again from the last yield statement that was returned.
The most difficult thing to understand is that generator and functions are not performing the same process. The function is executed sequentially, and the return statement is encountered or the last line of function statement is returned. The function that becomes generator, executes at each call next (), encounters a yield statement return, and executes again from the last yield statement that was returned.
iterators

There are several types of data that can be directly applied to a for loop: A class is a collection data type, such as list, tuple, dict, set, str, and so on; one is generator, including the generator and generator function with yield.

These objects, which can directly affect the for loop, are called iterated objects: Iterable.

You can use Isinstance () to determine whether an object is a Iterable object:

>>> from collections Import iterator
>>> isinstance ((x to X in range), iterator)
True
>>> isinstance ([], iterator)
False
>>> isinstance ({}, iterator)
false
>>> isinstance (' abc ', iterator)
false

Generators are iterator objects, but list, dict, str, although iterable, are not iterator.

The ITER () function can be used to turn the iterable of list, dict, str, etc. into iterator:

>>> Isinstance (ITER ([]), iterator)
true
>>> isinstance (ITER (' abc '), iterator)
true

You may ask why the data types such as list, dict, str are not iterator.

This is because the Python iterator object represents a stream of data that can be called by the next () function and continuously return the next data until the Stopiteration error is thrown when there is no data. This data stream can be thought of as an ordered sequence, but we can't know the length of the sequence in advance, we can only compute the next data on demand through the next () function, so the iterator calculation is inert and it will only be computed if the next data needs to be returned.

Iterator can even represent an infinitely large stream of data, such as all natural numbers. and using list is never possible to store all the natural numbers. Summary all objects that can be used for a for loop are iterable types; objects that can be used for the next () function are iterator types that represent a sequence of lazy computations; collection data types such as list, Dict, STR is iterable but not iterator, but a iterator object can be obtained by using the ITER () function. The python for loop is essentially a functional programming High-order function that is implemented by continually invoking the next () function

Variables can point to functions

>>> f = ABS
>>> f ( -10)
10

The function name is also a variable

>>> ABS =
>>> ABS ( -10)
Traceback (most recent call last):
  File "<stdin>", line 1, I n <module>
typeerror: ' int ' object is not callable

Incoming function
* * Since a variable can point to a function, and a function's argument can receive a variable, a function can receive another function as a parameter, a function called a higher order function. **

def add (x, Y, f): Return
F (x) + f (Y)

Call

>>> Add ( -5, 6, ABS)
11
return functionfunction as the return value

In addition to accepting functions as arguments, higher-order functions can return functions as result values.

def lazy_sum (*args):
    def sum ():
        ax = 0 for
        n in args:
            ax = ax + n return
        ax
    -return sum

When we call Lazy_sum (), we return not the sum, but the summation function:

>>> f = lazy_sum (1, 3, 5, 7, 9)
>>> F
<function lazy_sum.<locals>.sum at 0x101c6ed90 >

When the function f is called, the result of the summation is really calculated:

>>> f ()
25

In this example, we define the function sum in the function lazy_sum, and the internal function sum can refer to the arguments and local variables of the external function lazy_sum, and when Lazy_sum returns the sum of the functions, the related arguments and variables are stored in the returned function, which is called " The program structure of closure (Closure) has great power.

* * Please note that when we call Lazy_sum (), each call returns a new function, even if the same argument is passed in: * *

>>> f1 = lazy_sum (1, 3, 5, 7, 9)
>>> F2 = lazy_sum (1, 3, 5, 7, 9)
>>> f1==f2
False
Closed Bag

Note that the returned function refers to the local variable args within its definition, so when a function returns a function, its internal local variables are also referenced by the new function, so the closure package is simple and difficult to implement.

def count ():
    fs = [] for
    I in range (1, 4):
        def f (): Return
             i*i
        fs.append (f) return
    FS

F1, F2, F3 = count ()

>>> F1 ()
9
>>> F2 ()
9
>>> f3 ()
9
All of them are 9. The reason is that the returned function refers to the variable I, but it is not executed immediately. When 3 functions are returned, the variable I referenced is already 3, so the final result is 9.

One thing to keep in mind when returning a closure is that the return function does not refer to any loop variable, or to a variable that changes later.

What if you must refer to the loop variable? The method is to create a second function, with the function's argument binding the current value of the variable, regardless of the subsequent changes to the loop variable, the value that is bound to the function parameter is unchanged:

def count ():
    def F (j):
        def g (): Return
            j*j return
        g
    fs = []
    for I in range (1, 4):
        Fs.append (f (i)) # f (i) is executed immediately, so the current value of I is passed in F () return
    FS

And look at the results:

>>> F1, F2, F3 = count ()
>>> F1 ()
1
>>> f2 ()
4
>>> f3 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.