My Python study--fourth day

Source: Internet
Author: User

First of all, the previous three days of study content to review

1. Data structure based on Python

Number (int/float, including integers and floating-point numbers)

Boolean (Boolean = True/false)

String (str, enclosed with " or ")


Listing (list)

A list is a set of arrays enclosed in [] that are contiguous in memory and can be modified by adding or deleting them.

Dictionary (dict)

The dictionary is a k/v key-value pair that is enclosed in {}, which is randomly distributed in memory by hashing, is unordered, and can be modified by adding or deleting it.

Tuple (tuple)

Tuples are similar to lists, except that the elements of a tuple cannot be modified, and tuples use parentheses ()

2, the syntax of Python

Defining Variables A=1

If Else statement


If Boolean value:

True to do here

Else

False Execute here


For loop

Circular list or Dict


While loop

While Boolean value:

Boolean true, always executed

Break/continue


Debug Method (Print)


The Help () function and the Dir () function

The Help () function is a detailed description of the purpose of the function or module, and the Dir () function is a way of looking at the action within a function or module, and the output is a list of methods.


3. The difference between list and dict

List has order

Find, append quickly, insert, delete very slow, hit CPU cache probability big

Dict no order.

Find, modify, delete are quick


Dict->list:for Key,value in Dict.items ()

List turns into Dict:for index,value in enumerate (list)


4. File read

Open: Opening file

Read, ReadLine, ReadLines: Reading file contents

Write, Writelines: File Write

Close: Closing files

Tell () and Seek ()

When the file is opened, it can only be started at the beginning, each time read, ReadLine, ReadLines will move the pointer to the reading data place

Tell (): Returns the current position of the pointer where the file is located

Seek (#,whence=0): Move the # file pointer from a file, a positive number to the end of the direction of movement, negative numbers to the beginning of the direction of movement, if the whence parameter is set to whence set the starting position, 0 means the beginning of the file, 1 means the current position, 2 means the end of the file


Second, on the third day of statistics Nginx access log, get access to the top ten IP address, and in the format of the HTML presentation of the exercise to optimize

#!/usr/bin/python#coding:utf-8res = {} ' F = open (' Access.log ')                                #  Pre-optimized file open, close ... f.close () "With open (' Access.log ')   as f:                       #  optimized file Open, close     for line in f:         tmp = line.split ('   ')          ip,url = tmp[0],tmp[6]         "         if  (Ip,url)  in res:                        Data statistics  & before   #  optimizationnbsp;          res[(Ip,url)] += 1         else:             res[(Ip,url)] = 1         "         res[(Ip,url)] = res.get ((Ip,url), 0) +1      #   Optimized data statistics Res_list = res.items () # print res_list "                                                   #  before optimization, use the Bubble method to sort For j in range (one):     for i in range (Len (res_list)-1):         if  res_list[i][1] >&nbsP;res_list[i+1][1]:            res_list[i],res_ List[i+1]=res_list[i+1],res_list[i] "res_list = sorted (res_list,key=lambda x:x[1],reverse=true  #  use sorted function to sort i = 0html_str =  ' <table border= "1px" > ' # res_ after optimization List.reverse () for r in res_list[:10]:    i = i+1#  (' 218.200.66.204 ',  '/data/uploads/2014/0707/12/small_53ba21ee5cbde.jpg '),  1),     html_str +=  ' <tr><td>No%s</td> <td>%s</td><td>%s</td> <td>%s</td> '% (i,r[0][0],r[0][1],r[1]) html_str+= ' </table> ' html_f = open (' res.html ', ' W ') Html_f.write (HTML_STR) html_f.close ()


Third, function (fourth day focus)


Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of the code. Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.


Rules for defining functions:

The function code block begins with a def keyword followed by the function identifier name and parentheses ().

Any incoming parameters and arguments must be placed in the middle of the parentheses. The middle of the parentheses can be used to define default parameters.

The first line of the function statement can optionally use the document string-for storing the function description.

The function contents begin with a colon and are indented.

return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.


Grammar:

def func_name (parameters):

Func_suite

return [expression]

Example: Defining a function to implement factorial

def f (num): fact = 1 if Num<0:return "No negative factorial" elif Num==0:return 1 for i in Range (1,num+1): Fact *= I return fact


Parameters:

function type used when calling a function:


Required Parameters:

When a function is called, it must be passed in the correct order, and the passed in parameter must match the declared parameter

>>> def Hello (name): ... return ' hello ' +name...>>> hello (' world ') ' Hello World '


Keyword parameters:

keyword arguments are closely related to function calls, and function calls use keyword parameters to determine the values of the parameters passed in. Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.

>>> def hello (name,age): ... return ' Hello%s,your age is%s '% (name,age) ...>>> hello (age=20,name= ' Ali Ce ') ' Hello Alice,your age is 20 '


Default parameters:

when a function is called, the value of the default parameter, if not passed in, uses a predefined default value.

>>> def hello (name,age=20): ... return ' Hello%s,your age is%s '% (name,age) ... >>> hello (' Bob ') ' Hello Bob,your Age is 20 '


variable length parameter:

You may need a function that can handle more arguments than was originally declared. These parameters are called indeterminate length parameters.

* Start parameters, collect all remaining parameters (positional parameters), apply to the meta-ancestor

* * Start parameter, collect all remaining parameters (keyword parameter), apply to dictionary

>>> def hello (name,*msg): ... return ' Hello%s,your msg is%s '% (name,msg) ... >>> hello (' Catalina ', 20, ' Female ') "Hello Catalina,your msg is (A, ' Female ')"


Anonymous functions:

Lambda

Syntax:Lambda [arg1 [, arg2,..... argn]]:expression


Example: Write a function that asks for a sum of two numbers

>>> sum = lambda x,y:x+y>>> print sum (10,5) 15


Scope:

all variables of a program are not accessible in any location. Access permissions depend on where the variable is assigned . The scope of the variable determines which part of the program you can access which particular variable name. function Internal variables, first within the functions of the search, can not find to go to the global search , internal variables want to modify the global variable, just use global declaration . Avoid using global variables between multiple functions as much as possible


Example:

#!/usr/bin/python#coding:utf-8total = 0 #这是一个全局变量def sum (ARG1,ARG2): Total = Arg1 + arg2 # Total Here is the local variable in the print function is local variable: "," "," All return Totalsum (10,20) "Print" Letter The number is a global variable: ", total
[[email protected] python]# python examp.py function is a local variable: 30 outside the function is a global variable: 0


To change a local variable to a global variable:

num = 100                                              #  global variable Def func ():     global num                                         #  use Global to define local variables as global variables     num =  200                                          #  local variable     print numfunc () print num

Results:   

[email protected] python]# python examp3.py200200


Iv. using functions to transform the exercises in ' two '

Def oper_file (file_name):                             #  define functions, depending on the number of accesses to the IP , url sort     res = {}    with open (file_name)  as  f:        for line in f:             tmp = line.split ('   ')              ip,url = tmp[0],tmp[6]             res[(Ip,url)] = res.get ((Ip,url), 0) +1     return sorted (Res.items (), key=lambda x:x[1],reverse=true) def get_html (arr):                                     #  the sorted data into HTML format      tmpl =  ' <tr><td>No%s</td> <td>%s</td><td>%s</td>< Td>%s</td></tr> '         html_str =  ' 


HTML file:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/84/96/wKioL1eVqCviuxVBAAA4C5SLjDM287.png "title=" Html.png "alt=" Wkiol1evqcviuxvbaaa4c5sljdm287.png "/>



My Python study--fourth 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.