Collect and sort out some common Python methods and skills
1. Three Methods to reverse a string
1.1. Simulate the method in C ++ and define an empty string for implementation
Set an empty string, traverse the strings in the parameter from the back to the front, and merge them into new strings using the addition of strings.
Copy codeThe Code is as follows:
Def reverse (text ):
Str =''
Index = len (text)-1
While index> = 0:
Str + = text [index]
Index-= 1
Return str
1.2. Use Slicing
This is a feature in Python. The slice can take negative values. This uses the Slice Method and sets the step size to-1, so that reverse sorting is achieved.
Copy codeThe Code is as follows:
Def reverse_1 (text ):
Return text [:-1]
1.3. Usage list
The reverse Method of the List is used. First, the text is converted to the list, and then reversed by the reverse method. Then, the join method is used to join the list as a string.
Copy codeThe Code is as follows:
Def reverse_2 (text ):
Temp = list (text)
Temp. reverse ()
Return ''. join (temp)
2. Use reduce
Use anonymous functions and reduce ()
Copy codeThe Code is as follows:
Def reverse_3 (text ):
Return reduce (lambda x, y: y + x, text)
Print reverse_3 ("Hello ")
3. Four methods to traverse the dictionary
Copy codeThe Code is as follows:
Dict = {"a": "apple", "B": "banana", "o": "orange "}
Print "########## dict ######################"
For I in dict:
Print "dict [% s] =" % I, dict [I]
Print "########### items #####################"
For (k, v) in dict. items ():
Print "dict [% s] =" % k, v
Print "########## iteritems #################"
For k, v in dict. iteritems ():
Print "dict [% s] =" % k, v
Print "########## iterkeys, itervalues #######"
For k, v in zip (dict. iterkeys (), dict. itervalues ()):
Print "dict [% s] =" % k, v
4. Three Methods to traverse the list
Copy codeThe Code is as follows:
For key in lst:
Print key
For I in range (len (lst )):
Print lst [I]
For index, key in enumerate (lst ):
Print key // index is the index of the list
5. dictionary sorting method
The dictionary is sorted in the ascending order of values (from small to small by default ).
Copy codeThe Code is as follows:
Dic = {'A': 31, 'bc': 5, 'C': 3, 'asd ': 4, 'A': 74, 'D': 0}
Dict = sorted (dic. iteritems (), key = lambda d: d [1], reverse = True)
Print dict
// Output result:
[('A', 74), ('A', 31), ('bc', 5), ('asd ', 4), ('C ', 3), ('D', 0)]
Next we will break down the code
Print dic. iteritems () to obtain the [(Key, value)] list.
Then, use the sorted method and the key parameter to specify that the sorting is based on the value, that is, the value of the first element d [1. Reverse = True indicates that the system needs to be flipped. The default value is from small to large. If it is flipped, it is from large to small.
Sort dictionary keys:
Copy codeThe Code is as follows:
Dic = {'A': 31, 'bc': 5, 'C': 3, 'asd ': 4, 'A': 74, 'D': 0}
Dict = sorted (dic. iteritems (), key = lambda d: d [0]) # d [0] indicates the dictionary key
Print dict
# In sorted, the third optional parameter is reverse. True indicates sorting from large to small.
# Default reverse = False
6. subclass and parent class
The subclass constructor calls the initialization constructor of the parent class.
Copy codeThe Code is as follows:
Class A (object ):
Def _ init _ (self ):
Print "testA
Class B ():
Def _ init _ (self ):
A. _ init _ (self)
Subclass calls a function of the same name as the parent class
Copy codeThe Code is as follows:
Super (). fuleifunction ()
7. More flexible parameter transmission methods
Copy codeThe Code is as follows:
Func2 (a = 1, B = 2, c = 3) # default parameter
Func3 (* args) # accepts any number of parameters and transmits them in tuple mode.
Func4 (** kargs) # input the parameter in the form of a key-Value Pair dictionary
The asterisk prefix (*) is added to the variable. The called parameters are stored in a tuple () object and assigned to the parameter. When processing a parameter within a function, you only need to operate the tuple-type parameter (args here. Therefore, a function can handle any number of parameters without specifying the number of parameters.
Copy codeThe Code is as follows:
Def calcSum (* args ):
Sum = 0
For I in args:
Sum + = I
Print sum
# Call:
CalcSum (1, 2, 3)
CalcSum (1, 123,456)
CalcSum ()
# Output:
6
579
0
#################################
Def printAll (** kargs ):
For k in kargs:
Print k, ':', kargs [k]
PrintAll (a = 1, B = 2, c = 3)
PrintAll (x = 4, y = 5)
# Output:
A: 1
C: 3
B: 2
Y: 5
X: 4
Parameters in python can be combined in multiple forms. In mixed use, you must first pay attention to the function writing method, which must comply:
1. The parameter (arg =) with the default value must be after the parameter (arg) without the default value
2. The tuple parameter (* args) must be after the parameter (arg =) with the default value
3. The dictionary parameter (** kargs) must be after the tuples parameter (* args)
When a function is called, the parameter transmission process is as follows:
1. assign values to parameters without specified parameters in sequence
2. Assign the real parameter value of the specified parameter name (arg = v) to the corresponding form parameter.
3. Package redundant real parameters without specified parameters into a tuple and pass it to the tuples parameter (* args)
4. Package the redundant real parameters of the specified parameter name into a dict and pass them to the dictionary parameter (** kargs)
8. lambda expressions
Lambda expressions can be seen as an anonymous function.
Syntax format of lambda expressions:
Lambda parameter list: expression # There are no parentheses around the parameter list, no return keyword before the return value, and no function name
Copy codeThe Code is as follows:
Def fn (x ):
Return lambda y: x + y
# Call
A = fn (2)
Print a (3)
# Output
5
Analysis
: Fn (2) after the call, it is equivalent to a = lambda y: 2 + y, and then a (3) is called.
Equivalent to print lambda y: 2 + 3