1. The CMP function is a python-brought function that compares two parameters which is the size of a small
Print CMP (2, 3) # -1print cmp (2, 1) # 1print CMP (2, 2) # 0
If the first argument is smaller than the second one, it returns 1, two elements are equal, returns 0, otherwise 1
2. So you can use this function to customize your own comparison rules.
defcmp_country_size (Country1, Country2): Alist= ['United States','China','Canada','Russia'] returnCMP (Alist.index (Country1), Alist.index (Country2))PrintCmp_country_size ('China','Canada')
For example, here the Cmp_country_size function is used to compare which country has a larger area
Sorting in 3.python
The functions used in Python for sorting are sorted and Sort,sort are list methods, the difference being that sort is sorted in the original list, sorted is a new list to sort,
Their usage is the same:
def sort (self, cmp=none, Key=none, Reverse=false)
CMP is the rule of sorts, and key is sorted by which part of the list element, whether the reverse is reversed
items=[{'name':'Kevin',' Age':' the','Course':'中文版','Country':'Canada'}, {'name':'Tom',' Age':' the','Course':'Chinese','Country':'China'}]items.sort (CMP=LambdaX,y:cmp_country_size (x['Country'],y['Country'])orCMP (x[' Age'],y[' Age'])orCMP (x['name'],y['name']) )PrintItems
Sort the elements in items by country first, then by age and by name
Python complex multi-sorting