Python section III

Source: Internet
Author: User

Character Set fit

A collection is an unordered, non-repeating combination of data, and its main functions are as follows:

    • Go to the weight, turn a list into a set, and then automatically go heavy.
    • Relationship test, test the intersection of two sets of data, difference set, and the relationship between the set

Common operations

list_1 = [1,4,5,7,3,6,7,9]list_1=Set (list_1) list_2=set ([2,6,0,66,22,8,4])#print (list_1,list_2)###交集#Print (List_1.intersection (list_2))##并集#Print (List_1.union (list_2))###差集#Print (List_1.difference (list_2))##子集#list_3 = set ([1,5,7])#Print (List_1.issubset (list_2))#Print (List_1.issuperset (list_2))###对称差集: Remove intersection#Print (List_1.symmetric_difference (list_2))##print ("---------------------------")#List_4 = set ([5,6,7,8])#Print (List_3.isdisjoint (list_4))#intersectionPrint(List_1 &list_2)#UnionPrint(List_1 |list_2)#differencePrint(List_1-list_2)#Symmetric difference SetsPrint(list_1 ^list_2)#AddList_1.add (999)#Add multipleList_1.update ([888,777,555])#Delete anyPrint(List_1.pop ())#Specify delete PS Specifies that deleted items do not exist and will errorPrint(List_1.remove (1))#Specify DeletePrint(List_1.discard (888))Print(list_1)
file Operations
    1. Open the file, get the file handle and assign a value to a variable
    2. Manipulating a file with a handle
    3. Close File

The existing files are as follows

#Author:xp#data = open ("Yesterday", encoding= "Utf-8"). Read ()#file handle#f = open ("Yesterday", ' W ', encoding= "Utf-8")#Read [r]#data = F.read ()#Write [w: overwrite]#f = open ("Yesterday", ' W ', encoding= "Utf-8")#f.write ("I love Beijing Tian ' an gate, \ n")#F.write ("The sun rises in Tiananmen Square, \ n")#a = apped append#f = open ("Yesterday", ' a ', encoding= "Utf-8")#F.write ("The sun rises in Tiananmen Square")#data = F.read ()#print ('-----read ', data)#Close#f.close ()#f = open ("Yesterday", ' R ', encoding= "Utf-8")#before reading five elements#For I in range (2):#print (F.readline ())#Low loop#For Index,line in Enumerate (F.readlines ()):#If index = = 9:#print ('-------------')#Continue#print (Line.strip ())#Efficient Circulation#f = open ("Yesterday", ' R ', encoding= "Utf-8")#count = 0#For line in F:#if Count = = 9:#print ('-------------=============================== ')#Count +=1#Continue#print (Line.strip ())#Count +=1#tell[by character Count]#f = open ("Yesterday", ' R ', encoding= "Utf-8")#print (F.tell ())#print (F.readline ())##打印当前位置#print (F.tell ())##回到某个地点#f.seek (0)#print (F.readline ())##print (f.encoding)#print (F.fileno ()) #返回地址的一个编号#print (F.flush ()) #刷新#f = open ("Yesterday", ' W ', encoding= "Utf-8")#Specify truncation character position#f.truncate ()# readable and writable#f = open ("Yesterday", ' r+ ', encoding= "Utf-8")#print (F.readline ())#print (F.readline ())#print (F.readline ())#f.write ("------------diao---------")#F.write ()#print (F.readline ())

#可写可读
f = open ("Yesterday", ' w+ ', encoding= "Utf-8")
F.write ("------------diao---------1\n")
F.write ("------------diao---------1\n")
F.write ("------------diao---------1\n")
F.write ("------------diao---------1\n")
Print (F.readline ())

#a + Append Read and write
f = open ("Yesterday", ' A + ', encoding= "Utf-8")
#rb Read binary files
f = open ("Yesterday", ' RB ', encoding= "Utf-8")

The mode of opening the file is:

    • R, read-only mode (default).
    • W, write-only mode. "unreadable; not exist; create; delete content;"
    • A, append mode. "Readable; not exist" create; "only append content;"

"+" means you can read and write a file at the same time

    • r+, can read and write files. "readable; writable; can be added"
    • w+, write and read
    • A +, with a
With statement

To avoid forgetting to close a file after opening it, you can manage the context by:

With open ('log','r') as F:

This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.

Character encoding and transcoding

GBK need to convert UTF-8 format flow
1, first by encoding "decode" to convert to Unicode encoding
2, then by decoding "encode" converted to UTF-8 encoding
UTF-8 need to convert to GBK format process
1, first by encoding "decode" to convert to Unicode encoding
2, then by decoding "encode" to convert the GBK encoding

#!/usr/bin/env python#-*-coding:utf-8-*-Tim='Hello'#Convert to UTF-8 encodingPrint(Tim.encode ('UTF-8'))#Convert to GBK encodingPrint(Tim.encode ('GBK'))#To ASCII encoding (Error why?) because there is no ' hello ' character set in the ASCII code table ~ ~)Print(Tim.encode ('ASCII'))
What is a function?

function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, the specific difference, we will say later, the function of programming in English also has a lot of different names. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.

Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions

Characteristics:

    1. Reduce duplicate code
    2. To make the program extensible
    3. Make programs easier to maintain

Syntax Definitions:

#Author: XP
def Test (x, y    ): Print (x)     Print (y) Test (+)
#Author:xp##def func1 ():## "" "Testing1" ""#print (' in the Func1 ')#return 0##过程#def func2 ():#"" " testing2 " ""#print ("in the Func2")##x =func1 ()#y =func2 ()
function parameters and Local variables

Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

#Author:xpSchool ="oldboy edu." #Global Variablesdefchange_name (name):GlobalSchool#change to a global variableShcool ="Ma Linux"    Print("before change", Name,school) name="XP"#This function is the scope of the variable (local variable)    Print(" after change", name) name="XP"change_name (name)Print(name)Print("Shcool", school)
Recursive

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

# Author:xp def Calc (n):     Print (n)     if int (N/2) >0:        return calc (int (n/2))    print(  ",", N) Calc (10)
Results:

10
5
2
1

Recursive properties:

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion

3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

Higher order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

# Author:xp def Add (a,b,f):     return F (a) += Add (3,-6, ABS)print(res)123123

Python section III

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.