Regarding sort()

Jaime Fernandez del Rio jaime.frio at gmail.com
Mon May 25 03:51:42 EDT 2009


Hi Dhananjay,

Sort has several optional arguments, the function's signature is as follows:

s.sort([cmp[, key[, reverse]]])

If you store your data as a list of lists, to sort by the third column
you could do something like:

data.sort(None, lambda x : x[2])

For more complex sortings, as the one you propose, you need to define
a compare function, that determines if an object preceeds another or
not. In your case, something like:

def list_cmp( a, b) :
    if a[2] > b[2] :
        return 1
    elif a[2] < b[2] :
        return -1
    else : # a[2] == b[2]
        if a[5] > b[5] :
            return 1
        elif a[5] < b[5] :
            return -1
        else : # a[5] == b[5]
            return 0

data.sort(list_cmp)

should do the trick for you...

Jaime


On Mon, May 25, 2009 at 9: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.
>
> Thanking you in advance ........
>
> regards
>
>
>
>
> --
> --------------------------------------------------------------
> Dhananjay C Joshi
> Project Assistant
> Lab of Structural Biology,
> CDFD, Bldg.7, Gruhakalpa
> 5-4-399/B, Nampally
> Hyderabad- 500001, India
> Tel: +91-40-24749404
> Fax: +91-40-24749448
> --------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.



More information about the Python-list mailing list