Sort

obou at my-deja.com obou at my-deja.com
Wed Dec 6 08:25:34 EST 2000


In article <NlnX5.1444$yv1.2700363 at nnrp5.proxad.net>,
  "Alfred" <scj at mcom.mcom.fr> wrote:
> Hello world,
>
> I'm trying to sort a List of List, on the third col, but I don't find
how to
> do this.
>
> Please help me. ;)
>
> Greg
>
>

Probably not the cleanest way to do it, but you could implement a
wrapper for your list that implements a __cmp__ function. The __cmp__
function uses the cmp function on the item of the third col and returns
the value.

Sample code here.

# Create a list wrapper that implements a __cmp__ function
class MyListWrapper:
    # constructor, takes a list and the number of the col to sort with
    def __init__(self, a_list, sort_it = 2):
        self.my_list = a_list
        self.sort_it = 2

    # comparison function
    def __cmp__(self, listWrapper):
        return cmp(self.my_list[self.sort_it], listWrapper
[self.sort_it])

    # to let the items be accessed thru []
    def __getitem__(self, i):
        return self.my_list[i]

    # to return the list
    def getList(self):
        return self.my_list


# Test of the wrapper
if __name__ == '__main__':

# create the list
    l = [[5, 3, 8, 5],
         [7, 1, 0, 3],
         [7, 7, 4, 9],
         [8, 3, 5, 3],
         [2, 6, 8, 5]]

# convert the list of list to a list of "sortable list wrappers"
    for i in range(len(l)):
        l[i] = MyListWrapper(l[i])

# sort with standard sort function
    l.sort()

# convert back to a list of list
    for i in range(len(l)):
        l[i] = l[i].getList()

Hope this helps.

Olivier


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list