Some of the common methods of Python for your reference

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

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.