[Tutor] Rép. : Sorting Data in Databases

Ken G. beachkid at insightbb.com
Tue Nov 24 03:15:20 CET 2009


Luhmann wrote:
> I'd suggest you load all your data into a list of lists, then use the 
> .sort() method to sort it.
> The sort method takes a key= argument, which should be a function that 
> does some transformation to your data, then returns something to be 
> compared.
>
> for instance:
>
> >>> l=[[1,2,3],[2,3,4],[0,9,1]]
>
> >>> def cp(a):
>     return a[2]
>
> >>> l
> [[0, 9, 1], [1, 2, 3], [2, 3, 4]]
>
> >>> def cp(a):
>     return a[1]
>
> >>> l.sort(key=cp)
> >>> l
> [[1, 2, 3], [2, 3, 4], [0, 9, 1]]
> >>> def cp(a):
>     return a[0]
>
> >>> l.sort(key=cp)
> >>> l
> [[0, 9, 1], [1, 2, 3], [2, 3, 4]]
> >>>
>
Actually, I was fooling around with that today by adding to the list 
from the file and then sort.  I was using the following simplify method:

newlist = []

newlist = [
    456, 54, 8, 158, 878
    ]
(above data read from file)

newlist.sort()

print newlist
[8, 54, 158,  456, 878]

(still working adding to new file]

The actual sorted list has, as I recall, an apostrophe at the beginning 
and an \n at the end of every number I had.  I will be working on that. 

Thanks for your suggestion.

Ken
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091123/fb03a325/attachment-0001.htm>


More information about the Tutor mailing list