Python complex multi-sorting

Source: Internet
Author: User

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

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.