Thread: sorting

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2002
    Location
    Cleveland
    Posts
    112
    Rep Power
    12

    sorting


    Hey all

    How does sorting work? I saw this function but i have no idea how it works.

    python: items.sort( lambda a,b:cmp(a.Title(), b.Title()) )

    Thanks for any help.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    325
    Rep Power
    12
    sort can take in a comparison function.
    The comparison function takes in 2 arguments and returns them in sorted form.

    Eg.
    def copare(e1,e2):
    return e1-e2
    Eg. this will return a negative number to indicate it is to be reversed to sort it

    compare ('this', 'that')
    So to sort the array called 'items', you would use
    items.sort(compare)
    The only diff in ur code is that they used a 'lambda function' which is a function but without a name.) My compare function has the name 'compare' associated to the funtion object.
    I pass the function into the sort function as an argument. In their code, they create an anonymous function there and then to pass in as an argument. So their code could be re-written as:

    def mycompare(a,b):
    cmp(a.Title(), b.Title())

    items.sort( mycompare )
    Last edited by lazy_yogi; May 30th, 2003 at 10:21 AM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2002
    Location
    Cleveland
    Posts
    112
    Rep Power
    12

    got it!


    Thanks for you help, I appreciate it.

    B.A.

IMN logo majestic logo threadwatch logo seochat tools logo