A summary of common methods and techniques for Python

Source: Internet
Author: User
This article mainly describes the collection of some of the python common methods and techniques, this article explains three ways to reverse the string, four ways to traverse the dictionary, three ways to traverse the list, dictionary sorting methods and other Python common techniques and methods, the need for friends can refer to the next

1. Three ways to reverse a string
1.1. Simulate methods in C + +, define an empty string to implement
By setting an empty string, and then iterating through the string in the argument from backward to forward, using the addition of the string to merge into the new string

def reverse (text):    str = '    index = len (text)-1 while    index >= 0:        str + text[index]        index-= 1    return str


1.2. Using the Sectioning method
This is a feature in Python, the slice can take a negative value, this is the method of slicing, set the step to 1, so that the implementation of the reverse sort.

def reverse_1 (text):    return text[::-1]

1.3. Use the list

With the reverse method of the list, the text is converted to a list, then reversed by the reverse method, and then the string is concatenated through the join.

def reverse_2 (text):    temp = list (text)    temp.reverse ()    return '. Join (temp)

2. Using the Reduce
Using anonymous functions and reduce ()

def reverse_3 (text):    return reduce (lambda x, Y:y + x, text) print reverse_3 ("Hello")

3. Four ways to traverse a dictionary

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 ways to traverse the list

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. How to sort dictionaries
Dictionaries are sorted in the order of value values from large to small (default from small to sort).

DIC = {' A ': +, ' BC ': 5, ' C ': 3, ' ASD ': 4, ' AA ': 0}dict=, ' d ': Sorted (Dic.iteritems (), Key=lambda d:d[1], reverse = True) prin The results of the T-dict//output: [(' AA ', ', '), (' A ', ' + '), (' BC ', 5), (' ASD ', 4), (' C ', 3), (' d ', 0)]

Now let's break down the code.
Print Dic.iteritems () gets a list of [(Key, value)].
Then, using the sorted method, the key parameter specifies that the sort is sorted by value, which is the d[1 of the first element. Reverse = True indicates that it needs to be flipped, the default is small to large, flip the words, that is, from large to small.
To sort the dictionary keys (key):

DIC = {' A ': +, ' BC ': 5, ' C ': 3, ' ASD ': 4, ' AA ': 0}dict= sorted (Dic.iteritems (), Key=lambda d:d[0]) # D[0] means the dictionary key print D The third optional parameter in ict#sorted is reverse, true means ordering from large to small # default reverse = False

6. Subclasses and Parent classes
The subclass constructor calls the initialization constructor of the parent class

Class A (object):    def init (self):        print  "Testaclass B (A):    def init (self):        a.init (self)


A subclass calls a function with the same name as the parent class

Super (). Fuleifunction ()


7. More flexible method of parameter transfer

Func2 (A=1, b=2, c=3) #默认参数func3 (*args)         #接受任意数量的参数, passed in Func4 (**kargs) in a tuple       #把参数以键值对字典的形式传入

Precede the variable with an asterisk prefix (*), and the arguments are stored in a tuple () object and assigned to the parameter. Inside the function, the parameter needs to be processed, as long as the formal parameter of the tuple type (here is args) is done. Therefore, the function does not need to specify the number of arguments when it is defined, it can handle the case of any number of arguments.

def calcsum (*args):    sum = 0 for    i in args:        sum + = i        print sum# call: Calcsum (all in a) calcsum (123,456) calcsum ( ) #输出: 65790################################ #def printall (**kargs): For    K in Kargs:    print K, ': ', kargs[k] Printall (A=1, b=2, c=3) printall (x=4, y=5) #输出: A: 1c:3b:2y:5x:4

Python's parameters can be combined in a variety of forms, in the mixed use, first of all pay attention to the function of the wording, must abide by:

1. A formal parameter (arg=) with a default value must be followed by a formal parameter (ARG) without a default value
2. Tuple parameter (*args) must be after formal parameter (arg=) with default value
3. Dictionary parameters (**kargs) must be after the tuple parameter (*args)

When a function is called, the parameters are passed as follows:

1. Assigning arguments to parameters with no specified argument sequentially
2. Assign the arguments of the specified parameter name (ARG=V) to the corresponding formal parameter
3. Package the extra arguments without the specified parameters into a tuple passed to the tuple parameter (*args)
4. Package the arguments of the extra specified parameter name into a dict passed to the dictionary parameter (**kargs)

8. Lambda expression
Lambda expressions can be seen as an anonymous function
The syntax format for lambda expressions:
Lambda parameter list: expression #参数列表周围没有括号, no return keyword before returned value, no function name

DEF fn (x):    return lambda y:x + y# Call a = FN (2) print a (3) #输出5

Analysis
: After the FN (2) call, the equivalent of a = lambda Y:2 + y, and a (3) is called.
Equivalent to print lambda Y:2 + 3

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.