Regarding sort()

Chris Rebert clp2 at rebertia.com
Mon May 25 09:47:57 CEST 2009


On Mon, May 25, 2009 at 12:29 AM, Dhananjay <dhananjay.c.joshi at gmail.com> wrote:
> Hello All,
>
> I have data set as follows:
>
> 24       GLU    3       47      LYS     6       3.909233        1
> 42       PRO    5       785     VAL     74      4.145114     1
> 54       LYS    6       785     VAL     74      4.305017      1
> 55       LYS    6       785     VAL     74      4.291098      1
> 56       LYS    7       785     VAL     74      3.968647      1
> 58       LYS    7       772     MET     73      4.385121       1
> 58       LYS    7       778     MET     73      4.422980       1
> 58       LYS    7       779     MET     73      3.954990       1
> 58       LYS    7       785     VAL     74      3.420554       1
> 59       LYS    7       763     GLN     72      4.431955       1
> 59       LYS    7       767     GLN     72      3.844037       1
> 59       LYS    7       785     VAL     74      3.725048       1
>
>
>
>
> I want to sort the data on the basis of 3rd column first and latter want to
> sort the sorted data (in first step) on the basis of 6th column.
>
> I tried sort() function but could not get the way how to use it.
>
> I am new to programming, please tell me how can I sort.

Well, first you need to actually *parse* the data. Right now, the
lines are (apparently) just unstructured strings, which makes them
quite hard to manipulate.

#completely untested code:
afile = open("path/to/the/file", 'r')
data = []
for line in afile:
    fields = line.strip().split()
    for i in (0,2,3,5,6): #integer field indices
        fields[i] = int(fields[i])
    fields[-2] = float(fields[-2]) #float field index
    data.append(fields)
data.sort(key = lambda item: (item[2], item[5]) )


I would highly recommend you go through one or more Python tutorials
and/or read a book on Python (or programming generally).

Cheers,
Chris
-- 
http://blog.rebertia.com


More information about the Python-list mailing list