Sorting complex data structures in Python (similar to struct data structures in C)

Source: Internet
Author: User
Tags ticket

There are two main functions in Python: sorted and list member functions sort, except for some differences in invocation methods, the most notable difference is that sorted creates a sorted list and returns, while sort is a good order to modify the original list. The prototype of sorted is:

Sorted (iterable, Cmp=none, Key=none, Reverse=false)

The prototype of sort is:

List.sort (Cmp=none, Key=none, Reverse=false)

Where both CMP and key are function references, you can pass in the function name. Both of these functions operate on the members of the list. Reverse refers to whether to reverse the order.

Data structures such as structs or linked lists are often present in C, which can also be handled in Python.

As the data structure is like this:

   Study number   score 1  score 210000007      78
Then you can save the student's information with a list, i.e.

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

If you are simply sorting by a score, such as by a fraction of 2, you can:

If the input data is:

                     #学生总数10000001         #具体信息10000002 90 6010000011 85 8010000003 85 8010000004 80 8510000005 82 7710000006 83 7610 000007 90 7810000008 75 7910000009 59 9010000010 88 4510000012 80 10010000013 90 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]

The output is:

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

The code volume is much leaner than C, which is attributed to Python's powerful features (but time efficiency and space efficiency are generally lower than c in large amounts of data processing, but development is very efficient).

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

Title Description:

Enter the 1th line to give 3 positive integers, namely: N (<=105), that is, the total number of candidates, L (>=60), for the admission of the minimum score, that is, German and want $ are not less than L candidates are eligible to be considered for admission; H (<100), the priority line of admission-- The German and want $ are not below this line is defined as "only de full", such candidates by virtue of the total score from high to low ranking; want $, but the German division to the line of a class of candidates belonging to the "Desheng", but also according to the total number of candidates, but ranked in the first category after the candidate, Germany want $ are lower than H, but the score is not less than want $ candidates belong to "only Germany and death" "De Sheng", ranked by total, but ranked after the second category of candidates, other people who reached the minimum line L were ranked by total, but ranked after the third category of candidates.

Then n lines, each line gives a candidate's information, including: The ticket number, German points, want $, where the ticket number is a 8-bit integer, Germany is divided into the interval [0, 100] integer. The numbers are separated by a space.

Output format:

Output line 1th first gives the number of candidates to reach the minimum fraction m, followed by M, each line in the input format to output a candidate's information, candidates according to the rules indicated in the input from high to low sort. When a certain number of candidates in the same time, according to their German points in descending order; If the German points are also tied, the ticket number in the ascending output.


See the original title: 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]: RE Turn-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) el if 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:passfirstcla Ss.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:prin T 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 7810 000008 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 771000000 2 90 6010000014 66 6010000008 75 7910000001 64 90

However, there are several case timeouts for this code when submitting OJ, which is also a problem with Python (I don't know if there is a more efficient Python method). Why not use the key here, is because the problem of the comparison process through key is difficult to fully reflect, so with CMP, which also shows that the applicability of CMP more widely. However, because key only involves the calculation of a single list element, and CMP involves the calculation of two list elements, key is more efficient.

Sorting complex data structures in Python (similar to struct data structures in C)

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.