Sort complex data structures in Python (similar to the structure data structure in C) and python Data Structure

Source: Internet
Author: User

Sort complex data structures in Python (similar to the structure data structure in C) and python Data Structure

In Python, sorting mainly involves two functions: sorted and List member functions sort. Apart from calling methods, the most significant difference is that sorted creates a sorted list and returns it, sort modifies the order of the original list side by side. The prototype of sorted is:

sorted(iterable, cmp=None, key=None, reverse=False)

The sort prototype is:

list.sort(cmp=None, key=None, reverse=False)

Both cmp and key are function references, that is, the function name can be passed in. Both functions perform operations on the Members in the list. Reverse indicates whether to reverse the order.

Data structures such as struct or linked lists often appear in c, which can also be processed in Python.

For example, the data structure is as follows:

Student ID Score 1 score 210000007 90 78
You can use a list to save student information, that is

info = ['10000007', '90', '78']

If you simply sort by a certain score, such as by score 2, you can do this:

If the input data is:

14 # Total number of students 10000001 64 90 # details 10000002 90 6010000011 85 8010000003 85 8010000004 80 8510000005 82 7710000006 83 7610000007 90 7810000008 7910000009 9010000010 4510000012 88 10010000013 80 9910000014 66 60

Code:

#!/usr/bin/pythondef getKey( x ):    return int(x[2])num = input()list = []        for i in range(num):    info = raw_input().split()            list.append(info)list.sort( key=getKey )for i in list:    print i[0], i[1], i[2]

Output:

10000010 88 4510000002 90 6010000014 66 6010000006 83 7610000005 82 7710000007 90 7810000008 75 7910000011 85 8010000003 85 8010000004 80 8510000001 64 9010000009 59 9010000013 90 9910000012 80 100

The amount of code is much simpler than that of c, which is equivalent to the powerful functions of Python (however, in the case of massive data processing, the time efficiency and space efficiency are generally lower than c, but the development efficiency is high ).

This is sorting by passing the key, or by passing the cmp function. Let's look at a complicated example:

Description:

The input row 1st gives three positive integers: N (<= 105), that is, the total number of candidates; L (> = 60), is the lowest score for admission, that is, candidates with scores not lower than L are eligible to be considered for admission; H (<100), which is the preferred recording line-Germany and talent scores are not low. This line is defined as "only moral integrity". Such candidates are sorted in descending order of the total score by virtue; the first type of candidates who fail to score but fail to score the score belongs to "desheng talent", which is also ranked by the total score, but after the first type of candidates; the scores are lower than H, however, candidates with scores not lower than those with scores fall under the "talent, morality, and Death" but still have the "talent", sorted by the total score, but placed after the second type of candidates; other candidates whose scores reach the lowest threshold are also ranked by the total score, but ranked behind the third-class candidates.

In the next N rows, each row provides the information of a candidate, including admission ticket number, score, and talent score. The admission ticket number is an 8-digit integer, which is an integer within the range [0,100. Numbers are separated by spaces.

Output Format:

The output 1st rows first show the number of candidates reaching the lowest score, and then M rows. Each row outputs the information of one candidate according to the input format, candidates are sorted from high to low according to the rules described in the input. When a certain number of candidates have the same total score, the score is sorted in descending order. If the score is also the same, the admission ticket number is output in ascending order.


Original question see: http://pat.zju.edu.cn/contests/pat-b-practise/1015

Code:

#!/usr/bin/pythonfrom sys import exitdef myCmp( a, b ):    valuea = 2 * int(a[1]) + int(a[2])    valueb = 2 * int(b[1]) + int(b[2])        if valuea > valueb:        return -1    elif valuea == valueb:        if a[0] < b[0]:            return -1        else:            return 1    else:        return 1rawIn = raw_input().split()num = int(rawIn[0])jige = int(rawIn[1])prio = int(rawIn[2])firstClass = []secondClass = []thirdClass = []forthClass = []for i in range(num):    rawIn = raw_input().split()        if int(rawIn[1]) >= prio and int(rawIn[2]) >= prio:        firstClass.append(rawIn)    elif int(rawIn[1]) >= prio and jige <= int(rawIn[2]) <= prio:        secondClass.append(rawIn)    elif int(rawIn[1]) >= jige and int(rawIn[2]) >= jige and int(rawIn[1]) >= int(rawIn[2]):                thirdClass.append(rawIn)    elif int(rawIn[1]) >= jige and int(rawIn[2]) >= jige:        forthClass.append(rawIn)    else:        passfirstClass.sort(cmp=myCmp)secondClass.sort(cmp=myCmp)thirdClass.sort(cmp=myCmp)forthClass.sort(cmp=myCmp)        print len(firstClass) + len(secondClass) + len(thirdClass) + len(forthClass)for i in [firstClass, secondClass, thirdClass, forthClass]:    for j in i:        print j[0], j[1], j[2]exit(0)

Input:

14 60 8010000001 64 9010000002 90 6010000011 85 8010000003 85 8010000004 80 8510000005 82 7710000006 83 7610000007 90 7810000008 75 7910000009 59 9010000010 88 4510000012 80 10010000013 90 9910000014 66 60

Output:

1210000013 90 9910000012 80 10010000003 85 8010000011 85 8010000004 80 8510000007 90 7810000006 83 7610000005 82 7710000002 90 6010000014 66 6010000008 75 7910000001 64 90

However, this code has several case times out when submitting OJ, which is also a problem in Python (I don't know if there is a more efficient Python method ). The reason why the key is not used here is that the comparison process of this question is difficult to fully reflect through the key, so the cmp is used, which also shows that the cmp has a wider applicability. However, keys only involve the calculation of a single list element, while cmp involves the calculation of two list elements, so keys are more efficient.

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.