[Tutor] Sorting Data

Gregor Lingl glingl@aon.at
Mon, 19 Aug 2002 22:34:47 +0200


Alan Colburn schrieb:

>I have a quick, general question. Suppose I have a database of
>information--list, tuple, or dictionary--with each element (or value) being
>a list, i.e., a list of lists, a tuple or lists, or a dictionary of lists.
>Regardless, assume each of these data lists is ordered similarly. list1[0],
>list2[0], and list3[0] all represent, for example, a person's first name,
>and list1[1], list2[1], and list3[1] all represent a last name.
>
>What's a typical way to be able to sort the database by any list element? In
>the above example, I recognize I could sort by first name simply by using
>the .sort() command. (If the database was contained in a variable called
>MasterList, I could invoke MasterList.sort().) However, how would you sort
>by last name? And what if the lists making up the database had multiple
>entries (first name, last name, a date, text notes, etc.)?
>
>In most spreadsheet programs, a user can simply highlight a column and click
>an icon called "Sort" to accomplish the goal I'm asking about.
>
>Thank you, as always! -- Al
>
>p.s. I've asked a couple questions to the list during the last few weeks.
>Your responses have been very helpful!
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>
Another way to accomplish this is to provide your own comparison-function
as an argument to sort:

 >>> list = [[1,8],[2,7],[3,6],[0,9]]
 >>> l = list[:]
 >>> l.sort()
 >>> l
[[0, 9], [1, 8], [2, 7], [3, 6]]
 >>> def mycomp(l1,l2):
    a,b=l1[1],l2[1]
    if a<b: return -1
    elif a==b: return 0
    else: return 1

   
 >>> l = list[:]
 >>> l.sort(mycomp)
 >>> l
[[3, 6], [2, 7], [1, 8], [0, 9]]
 >>>

See for instance: 
http://www.python.org/doc/current/lib/typesseq-mutable.html
Regards, Gregor