Python fifth day

Source: Internet
Author: User
Tags generator


First:

1. The function of the co-process:

Yield is the result of a function as a generator.

An object with the ITER and next methods means that the object is an iterator, an iterator, and a generator.

If an object has only the Iter method, then this object is an iterative object.

Yield is to encapsulate the execution result of the function with the ITER and next methods, and an iterator can be obtained.

His functions are similar to return functions, can return a value, but the difference is that return can only be returned once, and yield returns multiple values.

The function is paused and the state of the run is also yield saved.

Example 1,

#yield

def func (count):

Print (' Start ')

While True:

Yield count

Count+=1

G=func (10)

Print (g)

Print (Next (g))

Print (Next (g))


Example 2:

#yield的表达式应用.

Def eater (name):

Print ('%s said: I started '%name ')

While True:

Food=yield

Print ('%s eat%s '% (Name,food))


Res=eater (' XZ ')

Print (Next (res))

Print (' ================ ')

Res1=next (RES)

Print (RES1)

>>

XZ says: I'm moving.

None

================

XZ Eat None

Non


The #yield的表达式, must be initialized before execution, or the value of None

#yield的表达式应用.

Def eater (name):

Print ('%s said: I started '%name ')

While True:

Food=yield

Print ('%s ate%s '% (Name,food))


Res=eater (' XZ ')

#第一阶段初始化 to start the generator in one place

Next (Res)**next is to give yield a value of none

#第二阶段, give yield value

Res.send (' Bun ')

>>

XZ says: I'm moving.

XZ Eat steamed buns

XZ eats bones.


Example 3:

#yield的表达式应用.

Def eater (name):

Print ('%s said: I started '%name ')

Food_list=[]

While True:

Food=yield food_list

Print ('%s ate%s '% (Name,food))

Food_list.append (food)

Res=eater (' XZ ')

#第一阶段初始化 to start the generator in one place

# Next (RES)

Res.send (None)

#第二阶段, give yield value

Print (Res.send (' Bun '))

Print (Res.send (' Vegetable soup '))

>>

XZ says: I'm moving.

XZ Eat steamed buns

[' Bun ']

XZ Eats vegetable soup

[' Steamed bun ', ' vegetable soup ']


Example 4:

#yield的表达式应用.

Def eater (name):

Print ('%s said: I started '%name ')

Food_list=[]

While True:

Food=yield food_list

Print ('%s ate%s '% (Name,food))

Food_list.append (food)


def func ():

Res=eater (' Xiaozhang ')

Next (RES)

While True:

Food_inp=input (' >> '). Strip ()

If not food_inp:continue

Res1=res.send (FOOD_INP)

Print (RES1)

Func ()

>>

Xiaozhang said: I'm moving.

>> Vegetable Soup

Xiaozhang Eat vegetable soup

[' Vegetable soup ']

>>


#装饰器解决初始化的问题:

Def init (func):

def warpper (*args,**kwargs):

Res=func (*args,**kwargs)

Next (RES)

return res

Return Warpper


@init

Def eater (name):

Print ('%s said: I started '%name ')

Food_list=[]

While True:

Food=yield food_list

Print ('%s ate%s '% (Name,food))

Food_list.append (food)


Def func1 ():

Res=eater (' Xiaozhang ')

While True:

Food_inp=input (' >> '). Strip ()

If not food_inp:continue

Res1=res.send (FOOD_INP)

Print (RES1)

Func1 ()


2, process-oriented: The core is the process of two words, the process is to solve the problem steps.

Designing programs based on process-oriented processes is like an industrial assembly line, a mechanical thinking.

Advantages: Clear, easy-to-read and process-structured procedures

Cons: Poor scalability, one process line solves only one problem

Application scenario: Linux kernel ..., single function


Example 1: Using a process-oriented approach, implementing GREP-LR ' Error '/dir/#显示文件中有error的列表文件


Import OS

Def init (func):

def warpper (*args,**kwargs):

Res=func (*args,**kwargs)

Next (RES)

return res

Return Warpper


First stage: Find the path to the file decision

@init

def search (target):

While True:

Filepath=yield

G=os.walk (filepath)

For Pardir,_,files in G:

For file in Files:

Abspath=r '%s\%s '% (pardir,file)

Target.send (Abspath)


Second Stage: Open file

@init

DEF opener (target):

While True:

Abspath=yield

With open (Abspath, ' RB ') as F:

Target.send ((abspath,f))


Phase III: Cyclic reading

@init

def cat (target):

While True:

Abspath,f=yield

For line in F:

Res=target.send ((Abspath,line))

If Res:break


Stage four: Filtration

@init

def grep (Patten,target):

Tag=false

While True:

Abspath,line=yield tag

Tag = False

If Patten in line:

Target.send (Abspath)

Tag=true


Fifth stage: Print the file name that the line belongs to

@init

def printer ():

While True:

Abspath=yield

Print (Abspath)

g = Search (opener (' Error ' encode (' Utf-8 '), Printer ())))

G.send (R ' H:\test ')


3. Recursive function:

The function itself is called directly or indirectly during the invocation of a function.

Lower recursion efficiency.

#直接

def func ():

Print (' from Func ')

Func ()

Func ()


#间接

def foo ():

Print (' from foo ')

Bar ()


def bar ():

Print (' from Bar ')

Foo ()

Foo ()


#递归

def age (N):

if n = = 1:

return 18

Else

Return (age (n-1) +2)


Print (age (5))


Recursion must have a definite condition, python no pseudo recursion


#递归

L=[1,3,[11,33],[11,[12,23,[44] []]

def search (L):

For item in L:

If type (item) is list:

Search (item)

Else

Print (item)

Search (L)


#二分法

L = [1,2,7,7,10,31,44,47,56,99,102,130,240]

#怎么判断某一个数字是否在列表内?


def binary_search (L,num):

Print (L)

If Len (L) > 1:

Mid_index=len (L)//2

If num > L[mid_index]:

L=l[mid_index:]

Binary_search (L,num)

Elif num < L[mid_index]:

L=l[:mid_index]

Binary_search (L,num)

Else

Print (' Find it ')

Else

If l[0] = = num:

Print (' Find it ')

Else

Print (' Not exit ')

Return

Binary_search (l,32)


Second, module and package

1, the module is to contain a Python definition and declaration of the file, file name is the module name plus the suffix of the py.

2, the module is imported by default is to execute the module file

3, the Import module did those things:

A. Execute source file

B. Create a global namespace with the original file

C, get a module name in the current location point to the namespace created by 2


4, from ... import

A, Advantages: Formal use of the source file name without prefix, easy to use

B, disadvantage: Easy to be confused with the name in the current file name space.

C, the horizontal bar only to the * function. Has a hidden effect, can use __all__=[] control * range.


5, the module loading

A, the module is only executed at the time of the first import, and then it is directly referenced in memory that has already been loaded.

Import Sys

Print (sys.modules) #存放的是已经加载到内存的模块字典


The order in which the modules are searched:

In-memory ==> built-in modules ==>sys.path

The custom module cannot have the same name as the module that the py comes with.

A py file has 2 purposes, scripts, and modules.

PY file as script Runtime: __name__ equals __main__

PY file as module call: __name__ equals module name

The package is another mode of the module, the package below has a _init_.py folder, is the package.

But in this is just the definition of py2.x, the folder that does not have _init_.py files in py3.x is also a package.


B, either import or From....import, whenever you encounter a point (.) It's all a bag. Import syntax, the left side of the point must be a package.

The package is the module, the import package is the import module.

OS module:

Os.path.abspath (__file__)#获取当前文件的绝对路径.


6, the parameters of the log module:

FileName: refers to creating Filehandler

FileMode: How the file Opens: Default to a can be specified as W

Format: The value handle uses for the display of the log.

DATEFMT: Specifies the date time format.

Level: Set the levels of the log

Stream: Creates a streamhandler with the specified stream,


Format of the log:

% (name) s logger name, not user name

% (Levelno) s log level in digital form

% (levelnames) s log level in text form

% (pathname) s calls the full path of the module of the log output function, may not have

% (filename) s the file name of the module that called the log output function

% (module) s call the module name of the log output function

% (funcName) s call the function name of the log output function

% (Lineno) s the line of code where the statement that called the log output function

% (created) F current time, floating point representation of standard Time with UNIX

% (relativecreated) d when the log information is output, the number of milliseconds since logger was created

% (asctime) s string form the current time, the default format is "2003-07-08 16:44:22,234" after the comma is milliseconds

% (thread) d thread ID, possibly BAA

% (threadname) s thread name, possibly None

% (process) d process ID, possibly None

% (message) s user-Output message


6. Python Regular:

\w matched alphanumeric and underlined

\w match non-alphanumeric underline

\s matches any white space character, equivalent to [\t\n\r\f]

\s matches any non-null character

\d matches any number, equivalent to [0-9]

\d matches any non-numeric

\a Match string start

\z matches the end of the string, if there is a newline, matching only the end string to the wrapped money.

\z Match string End

\g match the last match completed position

\ n matches a line break

\ t matches a tab

^ matches the beginning of the string

$ matches the end of a string

. Matches any character, except the line break, when re. When the Dotall tag is specified, it can match any character that includes a line feed.

[..] Used to represent a set of characters, list [AMK] separately, match A or M or K

[^..] Characters not in [], [^123] matches numbers other than 123

* Match 0 or more expressions

+ Match one or more expressions

? Match 0 or 1 times expression

{n} matches N-times expression

{n,m} matches n times to M-th expression

A|b match A or b

() matches the expression in parentheses and also represents a group.


This article from "Man should self-reliance" blog, please be sure to keep this source http://nrgzq.blog.51cto.com/11885040/1953216

Python fifth day

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.