Fifth day of basic Python learning

Source: Internet
Author: User
Tags shallow copy

Article directory:

5.1-depth Copy

5.1.1 Shallow Copy

5.1.2 Deep Copy

5.2 Collection Set

5.2.1 Update Set Collection _ Add

5.2.2 Update

5.2.3 Remove, Pop, clear, Del

5.2.4 intersection, and set

5.2.5 difference Set, symmetric difference set

5.2.6 Hyper-Set, subset

5.3 Functions:

5.3.1, Concept

5.3.2, creating

5.3.3, Parameters

The reture of 5.3.4 and functions

5.3.5, defining domains


# symbol Description

() #元组 Usage: (' xx ', ' yy ') not modifiable

[] #列表 usage: [' xx ', ' yy '] can be modified, the list must be hash, list and dictionary is not hash

List creation: a=[1,2]

B=list ([up])

{} #字典 Usage: {' xx ': ' yy ', (' zz ': ' DD ')} modifiable fields


5.1-depth Copy


5.1.1 Shallow copy = equivalent to soft link

# Variables in the list is equivalent to a file, int and STR is equivalent to a directory,

# (Soft links can name the directory more than the file itself, but if you modify the file then A and B will be modified at the same time).

A = [[1,2],3,4]

Print (a)

Printed: [[1, 2], 3, 4]

b = A.copy ()

b[1]=321

Print (b)

The result is: [[1, 2], 321, 4]# Soft Link directory name changed and will not affect the original directory

Print (a)

The results are as follows: [[1, 2], 3,4] # B Modifying a without modification is normal.


# But if you modify the list in a variable, it modifies the value in the memory, and a and B modify the

B[0][1] = 234

Print (b)

Print (ID (b[0][1))# The result is: 13,889,648,802 memory results are the same


Print (a)

The printed result is: [[1, 234], 321, 4] # changed the soft link file, then 2 files will also be called

[[1, 234], 3, 4]

Print (ID (a[0][1))) # The result is: 1388964880

# equivalent to a linked file, modify B is also equivalent to modifying a


5.1.2 Deep copy = Full clone

Variable = copy.deepcopy (variable to copy) # Complete cloning of one data


5.2 Set

Set: A set of different elements formed together, is the basic data type of the PY

# Redo function, when there are two identical elements will remove the duplicate string

# must be a hash string, set is unordered and can only be accessed or judged by looping through or using in and not

# Set cannot be a key


5.2.1 Update Set Collection _ Add

A = ["A", "B"]

C=set (a)

C.add ("C")

Print (c) result: {' B ', ' A ', ' C '}


5.2.2 Update

C.update ("AB1")

Print (c) result: {' B ', ' 1 ', ' A ', ' C '}

# AB1 is added as a sequence, there are duplicates not added to the sequence, no duplicates are added directly to the list


C.update ([123,321]) # when it is a list, it joins the sequence as a whole into the variable, with duplicates and does not add

Print (c)# {321, ' B ', ' A ', 123}


5.2.3 Remove, Pop, clear, Del

C.remove ("a") result: {' B ', ' 1 ', ' C '}

C.pop () result: randomly deletes a

C.clear ()# Result: Empty list return set ()

del c # directly delete the variable, print the error because it's gone.


5.2.4 intersection, and set

A=set ([1,2,3,4,5])

B=set ([1,2,3,4,6])

Intersection: Print (A & B) # {1, 2, 3, 4}

Assembly: Print (A | b) # {1, 2, 3, 4, 5, 6}


5.2.5 difference Set, symmetric difference set

Difference set: Print (A.difference (b)) in a but bot B # a There's no printout of B

Second method: Print (A-B)

# {5} and vice versa

Symmetric differential set: print (A.symmetric_difference (b)) AB does not print, only print a string or numeric value that it does not share

Second method: Print (A^B)

# {5, 6}


5.2.6 Hyper-Set, subset

Print (A.issuperset (b))# A is not completely inclusive B, no return False equals a>b

Print (A.issubset (b))# A is not a subset of B equals a<b


Name1=set (["Xiong", "Wei", "Hua", "FA"])

Name2=set (["Xiong", "Yua", "Yuan", "Hua"])


# subset # To determine if two fields are equal

Print (name1<name2) # False


# Parent Set # Determines whether two fields are equal

Print (name1>name2) # False


# and set # after printing to go back to the

Print (name1 | name2) # {' Hua ', ' Xiong ', ' yuan ', ' Wei ', ' fa ', ' Yua '}


# intersection # Common

Print (Name1 & name2) # {' Hua ', ' Xiong '}


# difference # Subtract the same field from set 2 with Set 1, and take out a collection that is not related to 2

Print (name1-name2) # {' Wei ', ' FA '}


# symmetric difference Set # take out A and b Yes, print a string that doesn't have two sets

Print (name1 ^ name2) # {' Yuan ', ' yua ', ' fa ', ' Wei '}


# Manually enter some strings to compare with a self-defined string

Ins=[]b=set ([' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']) while True:a=input ("test:") if a = = "Q": Break Ins.append (a) ins=set (INS) Print (Ins > B)

5.3 Functions:

5.3.1, Concept

Role:

1. Reduce duplication of code

2, easy to modify, easy to expand

3. Maintain Code consistency

Naming rules

The function name must begin with an underscore or a letter, can contain any combination of letters, numbers, or underscores, and cannot use any punctuation

Function names are case-insensitive;

The function name cannot be a reserved word.


5.3.2, creating

def f (): # DEF is a define abbreviation F () means the function name () can be used to pass parameters

Print ("Hello World") # function body, all the code below belongs to the F function


F ()# Call function, without (), directly with F then it is represented as a variable

5.3.3, Parameters

# Note: 1, the number of parameters, the argument must be defined how many

2, the call should be strictly case-sensitive

3, the dictation parameters must be followed by other parameters

4, indefinite long parameters, fixed format: (*args No named parameters left, **kwargs have named parameters put to the right), if there are default parameters left


# must parameter (keyword argument): The parameter must be passed into the function in the correct order, and the number of calls must be the same as when declared

def add (x, y): # Add (x, y) parameter

Print (X+y)

def (3,5)# arguments


def test1 (name,age):

Print ("Name:%s"% name)

Print ("Age:%d"% of age)


Test1 ("Xiong", 123)


Print Result: Name:xiong

Age:123


# Default Parameters:

def test1 (name,age,sex= "man"):

Print ("Name:%s"% name)

Print ("Age:%d"% of age)

Print ("Sex:%s"% sex)


Test1 ("Xiong", 123)

Print Result: Name:xiong

Age:123

Sex:man


# Indefinite length parameter: (*args) # args can name * indicates indefinite length parameter

(*arges): No named parameter # is a tuple when saved to args

(**kwargs): Dictionary with named parameter # saved to Kwargs

def test2 (*args): print (args) test2 (1,2,3,4,5,6) # The results are: (1, 2, 3, 4, 5, 6)

##################### Example 2 #####################

def test3 (**kwargs): Print (Kwargs) test3 (name= "Xiong", age=123,sex= "man") # Print Result: {' name ': ' Xiong ', ' age ': 123, ' sex ': ' m An '}

##################### Example 3 #####################

def test3 (**kwargs): For Te in Kwargs:print (Te, ":", Kwargs[te]) test3 (name= "Xiong", age=123,sex= "man") # Print Results: Name:xiong age:123 Sex:man

##################### Example 4 #####################

def test4 (*args,**kwargs): Print (Args,kwargs) test4 (1,2,3,4,name= "Xiong", age=123,sex= "man") # Print Result: (1, 2, 3, 4) {' Name ' : ' Xiong ', ' age ': 123, ' sex ': ' Man '}

##################### Error--Example 5 #####################

def test4 (name,sex= "man", *args,**kwargs): Print (Name,sex,args,kwargs) test4 (name= "Xiong", sex= "man", 1,2,3,4,age= 123) # Print Result: syntaxerror:positional argument follows keyword argument


# Priority: Def function name (key parameter, default parameter, no named parameter, named parameter)

#示例 def test (te1,age= ' male ', 123,job= ' IT ')


######### when there is a default value in the middle, if you do not specify it or will print an error,

def test4 (name,sex= "man", *args,**kwargs): Print (Name,sex,args,kwargs) test4 ("Xiong", 1,2,3,4,age=123)

The reture of 5.3.4 and functions

Effect: 1, End Function

2. Return an Object


Note: 1. If there is no return in the function, it will return a none by default

2, if return has more than one object, then Python will help us encapsulate multiple objects into a tuple to return


5.3.5, defining domains

The function has its own domain, if it is not.

The scope is divided into four kinds of situations: LEGB

l:local, local scope, which is the variable defined in the function;

E:enclosing, the local scope of the nested parent function, which is the local scope of the ancestor function that contains the function, but not the global;

G:globa, a global variable, is a variable defined at the module level;

B:built-in, the variables inside the system fixed module, such as int, ByteArray, etc. The order of precedence for a search variable is: scope local > Outer scope > Global >python Built-in scope in the current module, that is, LEGB


Outer built-in--global scope--enclosing local scope--local area scope


Local variables cannot modify global variables

Local to change global variables need to add one global variable

If it's in enclosing, then you need to add a nonlocal variable name


Module: Remove Current time

Import time

Time_format = '%y-%m-%d%x '

Times = Time.strftime (Time_format)

Print (Times)


# function, set a function time, save it to the test file, will print start funcation to the screen

#!/usr/bin/env python#-*-coding:utf-8-*-def Logger (n): Import time Time_format = "%y-%m-%d%x" times = Time.st Rftime (Time_format) with open ("Test file", ' a ', encoding= ' Utf-8 ') as F:f.write ("%s Funcation1%s \ n"% (times,n)) def F                      UN1 (n): Print ("Start funcation 1") Logger (n) fun1 (1) # Print results open test file 2017-09-12 14:13:33 funcation1 1 #%s times Parameters for the%s n function parameter

# Implement the addition of indefinite long functions

def test2 (*args): number = 0 for i in Args:number + = i print (number) test2 (1,2,3,4,5,6) # Pass a bunch of integers to the test2 function, protect Save to Args is a tuple format with a For loop overlay


This article is from the "Xiong" blog, make sure to keep this source http://xiong51.blog.51cto.com/5239058/1964772

Fifth day of basic Python learning

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.