Python development [Notes]: sort Sorting Algorithm (cmp, key, reverse), pythoncmp

Source: Internet
Author: User

Python development [Notes]: sort Sorting Algorithm (cmp, key, reverse), pythoncmp
Sort

The sorting function is often used in the program. Python provides the sort and sorted functions, one in-situ sorting and one Returning New results after sorting.

1. Parameters

Function prototype:

sort([cmp[, key[, reverse]]])
  • This means that the sort method accepts three parameters, which can be omitted. The default value is ascending order.
  • The first parameter cmp is a comparison function. The comparison between the two parameters (list elements) is intuitive for the comparison of built-in types such as integers, but for the comparison of custom types, define a comparison function by yourself. The function returns 0, which means that two numbers are equal and negative values are returned. That is, the first parameter is small, and the first parameter is placed behind the second parameter.
  • The second parameter key compares the attributes of the list element.
  • The third parameter, reverse, is of the bool type, indicates whether to reverse (reverse order)

① Cmp parameter example:

# Cmp function. Compare the two values! You can only run s = [1, 2, 3, 4, 5] s on python2.0. sort (cmp = lambda a, B: cmp (B, a) print s # [5, 4, 3, 2, 1]

② Common parameter key and reverse usage, code:

# Key indicates whether the reverse sorting method is reverse. li = ['x11', 'abc323', 'e26', 'mongoddd ', 'fstgd2'] li. sort (key = len, reverse = True) # sort by length, from large to small print (li) # ['abc323', 'mongoddd ', 'fstgd2 ', 'x11', 'e26'] li. sort (key = lambda x: x [-1]) # key can specify the lambada Function x as the print (li) of each element in the list) # Sort the last character of an element # ['x11', 'fstgd2', 'abc323', 'e26', 'mongoddd '] li = zip (range (10 ), range (10) [:-1]) # The elements in the list are sorted by print (li, type (li) # <zip object at 0x000000E7F75504C 8> <class 'zip'> li = list (li) print (li) # [(0, 9), (1, 8), (2, 7 ), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)] li. sort (key = lambda x: x [-1]) print (li) # [(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)] # ** note! By default, sort also sorts the ancestor in the list. sort () print (li) # (0, 9), (1, 8), (2, 7), (3, 6), (4, 5 ), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)]

The key parameter can be: key = int, key = len, key = lambda...

 

2. Sorting

① How to output the key-value in dict from small to large according to the value?

dic = {'z':1, 'y':4,'x':2,'g':3,'sg':3}dic= sorted(dic.items(),key=lambda x:x[1])print(dic)# [('z', 1), ('x', 2), ('sg', 3), ('g', 3), ('y', 4)]

Convert the data into a dictionary after sorting:

from collections import OrderedDictdic = {'z':1, 'y':4,'x':2,'g':3,'sg':3}dic= OrderedDict(sorted(dic.items(),key=lambda x:x[1]))print dic# OrderedDict([('z', 1), ('x', 2), ('sg', 3), ('g', 3), ('y', 4)])for k,v in dic.items():    print k,v# z 1# x 2# sg 3# g 3# y 4

② Specify a string containing only uppercase and lowercase letters and numbers and sort it to ensure:

  • All lowercase letters are in front of uppercase letters.
  • All letters are in front of the number
  • All odd numbers are before the even number.
S = "Sorting1234" def sort_str (x): # Each element input by x if x. isdigit (): if int (x) % 2 = 0: return (4, x) # The returned result is the ancestor. The ancestor can be sorted return (3, x) elif x. islower (): return (0, x) elif x. isupper (): return (1, x) li = sorted (s, key = sort_str) print (li) # ['G', 'I', 'n ', 'o', 'R', 't','s ', '1', '3', '2', '4'] string = ''. join (li) print (string) # ginortS1324

Simpler code:

s = "Sorting1234"s ="".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x)))print(s)# ginortS1324

  

 

 

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.