A summary of some knowledge points in Python (1) __python

Source: Internet
Author: User
Tags abs closure stdin wrapper
about how dictionaries and lists are used differently
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;  (data structures are linked and sequential) with
small footprint and little waste of memory.
So, Dict is a way of exchanging space for time.

dict can be used in many places where there is a need for high-speed lookups, almost everywhere in Python code, and it is important to use dict correctly, and the first thing to remember is that dict key must be immutable.

This is because Dict calculates the storage location of value based on key, and if the same key is calculated differently each time, the dict is completely messed up. This algorithm, which uses the key to compute the position, is called a hash algorithm.

to ensure the correctness of the hash, the object as a key cannot be changed. In Python, strings, integers, and so on are immutable, so it's safe to be a key. The list is variable and cannot be a key:
List-generatedThe list-generation, comprehensions, is a very simple, powerful build that Python can use to create a list.
General Generation
>>> [x * x for x in range (1, one)]
[1, 4, 9,, M, M,, and I]

plus if judgment for screening
&G t;>> [x * x for x in range (1, one) if x 2 = 0]
[4, +, M, two] the

iteration object corresponds to  the nesting of the For loop
>& gt;> [M + N for m in ' ABC ' for n in ' XYZ ']
[' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']

exercise after class

Input:
L1 = [' Hello ', ' world ', ' apple ', None]
output: [
' Hello ', ' world ', ' apple ']
test:
[X.lower () for X i n L1 if Isinstance (x, str)]
Build Device

With a list generation, we can create a list directly. However, the list capacity is certainly limited by the memory limit. And, creating a list of 1 million elements, not only takes up a lot of storage space, but if we just need to access the first few elements, the space behind most of the elements is wasted.

So if the list element can be calculated according to some algorithm, then whether we can continue to calculate the subsequent elements in the process of the loop. This eliminates the need to create a complete list, which saves a lot of space. In Python, this loop-side computing mechanism is called the generator: Generator.

How the Builder is created:

There are a number of ways to create a generator.  The first method is simple, as long as you change a list-generated [] to (), you create a generator:

>>> L = [x * x for x in range ()]
>>> l
[0, 1,  4, 9,,,,
>>> g = (x * x for x in range ())
>>> g
<generator Object <genexpr> at 0x1022ef630>

call Builder: The
    generator is called by Next (g)  , and the desired content is  thrown when it iterates to the last element stopiteration Exception to end iteration
    >>> Next (g)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <  Module>
    stopiteration

uses a for loop to iterate the generator
>>> g = (x * x for x in range ())
>>> for n In G: ...     Print (n)


uses the builder to complete the Fibonacci pull out series
def fib (max):
    N, a, b = 0, 0, 1 while
    n < max:
        yield b
        A, B = B, A + b
        n = n + 1 for

i in Fibz (5):
    Print I

the difference between a generator function and a normal function


Generator is a very powerful tool, in Python, you can simply change the list generation to
generator, or you can use the function to implement complex logic generator.

to understand how generator works, it is to constantly compute the next element in the process of a For loop
and end the For loop in the appropriate condition. For a function to generator, the return statement is encountered or executed to the last line of the function body, the instruction that ends the generator, and the For loop
ends.

Normal function call returns the result
generator function call returns the object of a generator
a simple analysis of higher order functions

A function can accept another function as an argument, and this function is called a higher order function.

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

x =-5
y = 6
f = ABS
f (x) + f (Y) ==> abs ( -5) + ABS (6) ==> ; Return
11
Built-in functions

Use of the map and reduce functions:
The map function: a iterable (which in turn takes the elements of a later iteration object to the previous function) returns a second iterator iterator, which is inert to reduce the use of the memory space, and the iterator is lazy
Simple example:

>>> def f (x):
...     return x * x ...
>>> r = Map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list (R) [1, 4, 9, 16, 25, 36, 49, 64, 81
]
See the use of reduce again. Reduce functions a function in a sequence [x1,x2,...] , this function must receive two parameters, reduce to continue the result and the next element of the sequence cumulative calculation, the effect is:
>>> from functools import reduce
>>> def add (x, y):
...     return x + y
...
>>> reduce (add, [1, 3, 5, 7, 9])

Convert a string to an integer using map and reduce coordination

From Functools import reduce

def char2num: "Return
    {' 0": 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8, ' 9 ': 9}[s]  # Follow the key to take value

def str2int (s): return
    reduce (lambda x, y:x * + y, map (Char2num, s))

practice after Class

Using the map () function, the user entered the nonstandard English name into the first letter uppercase, other lowercase canonical names.
input: [' Adam ', ' Lisa ', ' Bart '],
output: [' Adam ', ' Lisa ', ' Bart ']:

def normalize (name):
    return Name.lower (). Title ()
L1 = [' Adam ', ' LISA ', ' BarT ']
L2 = list (map (normalize, L1))
print L2
Use map and reduce to write a str2float function that converts the string ' 123.456 ' to a floating-point number 123.456:

def str2float (s):
    nums = map (Lambda ch:char_to_ Float[ch], s) point
    = 0
    def to_float (f, N):
        nonlocal point
        if n = = 1: Point
            = 1 return
            f
        if P  oint = 0: Return
            f * Ten + n
        else: Point
            = point * "
            F + n/point return
    reduce" (To_float, Nums, 0.0)

print (Str2float (' 0 ')) print (
str2float (' 123.456 ')) Print
(str2float (' 123.45600
')) Print (Str2float (' 0.1234 '))
print (Str2float ('. 1234 '))
print (str2float (' 120.0034 '))




def demo (m): "" "The
judge is not a palindrome number" ""
    n = List (str (m))
    n.reverse ()
    print n
    if "". Join (n) = = str (m):
        return True


Filter (demo, list)
sorted sort of after-school exercises
Sort by name
L = [(' Bob ', M], (' Adam ', sorted), (' Bart ', $), (' Lisa ', ")]
(L,key=lambda x:x[0))  The function \ Dict.items () that iterates through the elements of each list and passes it to the key is  returned with a tuple of elements in a list list
higher order function return function

The nesting of functions forms the concept of closures, and the results of multiple calls between closures are unaffected

In addition to accepting functions as arguments, higher-order functions can return functions as result values. The adorner is a special higher order function with a nested set of functions to combine

However, when using a higher order function to return a function, you need to note:

The closure

notes 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.

Another issue to note is that the returned function does not execute immediately, but until F () is invoked. Let's look at an example:
def count ():
    fs = []
    for I in range (1, 4):
        def f (): Return
             i*i
        fs.append (f)
    Return FS

F1, F2, F3 = count ()
in the example above, each loop creates a new function, and then returns the 3 functions that were created.

you may think that calling F1 (), F2 () and F3 () results should be 1,4,9, but the actual result is:

>>> F1 ()
9
>>> F2 ()
9
>>> f3 ()
9 are

all 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, using the function's arguments to bind the current value of the variable, and the value bound to the function parameter will not change, regardless of subsequent changes to the loop variable:
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


    summary

A function returns a result of a calculation, or it can return a function.

when you return a function, keep in mind that the function is not executed, and do not refer to any variables that may change in the return function
a point in the anonymous function

Function name can be used to get the name of a function

@functools. Wraps (func) uses wraps (func) to decorate the internal functions used

Full-edition Adorner
import Functools

def log (func):
    @functools. Wraps (func)
    def wrapper (*args, **kw):
        Print (' Call%s (): '% func.__name__)
        return func (*args, **kw) return
    Wrapper
use of the SYS module

The SYS module has a argv variable that stores all the parameters of the command line with the list. ARGV has at least one element because the first argument is always the name of the. py file. Use the Solt property to display properties that might be bound to be tired

Class Student (object):
    __slots__ = (' name ', ' age ') # Use tuple to define a property name that allows binding


>>> s = Student () # Create a new instance
&G t;>> s.name = ' Michael ' # binding attribute ' name '
>>> s.age = 25 # Binding attribute ' age '
>>> s.score = 99 # binding attribute ' SC Ore '
traceback (most recent call last):
  File "<stdin>", line 1, in <module>
attributeerror: ' Student ' object has no attribute ' score '



because ' score ' is not placed in __slots__, so the score attribute cannot be bound, and attempting to bind score will get the Attributeerror error.

use __slots__ to note that the properties defined by __slots__ only work on the current class instance and do not work on inherited subclasses:

Mkvirtualenv.bat–python==c:\python\python36-32\python.exe PY3 Specifies the version number of the installation use an enumeration class to determine the use of the Meta class and where to use the Meta class

Redis
mongod
mysql
flask
Django
restful-api
Unit Test
document Test 


def ABS (n):
    '
    Function to get absolute value of number.

    Example:

    >>> ABS (1)
    1
    >>> abs ( -1)
    1
    >>> abs (0)
    0
    ' ' Return
    N if n >= 0 else (-N)


    definitely tells the caller of the function the expected input and output of the function.

    also, the Python built-in document test (Doctest) module can directly extract the code from the annotation and execute the test.
file read and write operations
  use for else: when the for
    statement is executed normally, the else statement can execute normally, 


    instance: for item in
        Range:
            print (item)
        Else: Print
            ("Else")
        this statement  will print out the value of item and else for 


        item in []:
            print (item)
        else:< C35/>print ("Else")
        this will also print out else for the


        item in range:
            print (item)
            if item = =
                break
        Else:
            print ("Else")
        if the For loop is interrupted, then this else can  no longer be used


Related Article

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.