Elegant Python-how to sort multiple conditions in ascending or descending order

Source: Internet
Author: User

Previously, when collecting statistics and exporting the consumption of server players in each region, you must sort them in ascending order and in descending order.
This is the requirement. The partition is in the descending order. If the partition server is the same, the consumption is in the descending order.
The implementation method is to use Python sortAlgorithmIt is a stable sorting that sorts data multiple times. Secondary Conditions are arranged first, and primary conditions are arranged later.
There is also a more concise method for one stream, but it is only effective when the data to be sorted is a numerical value. This method adds a negative number in front of the opposite number.

BelowCode.

# Assume that the data is as follows. Data = ''' server, player ID, cumulative consumption 3, A, 23801, B, 119004, E, 32501, K, 1004, J, 5992, M, 8723, f, 55601, Y, 2500 ''' items = [X. split (',') for X in filter (none, Data. split ('\ n') [1:] # Remove the empty line and ignore the first line and convert the string into a two-dimensional array # method 1 items. sort (Key = Lambda X: int (X [2]), reverse = true) # consume items first. sort (Key = Lambda X: int (X [0]) # Then the partition server prints '\ n '. join ([','. join (x) for X in items]) print '-----------' # method 2 items = sorted (items, key = Lambda x :( int (X [0]), -int (X [2]) print '\ n '. join ([','. join (x) for X in items])

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.