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

    Join Date
    Jul 2003
    Location
    Questioner's home
    Posts
    89
    Rep Power
    12

    Sort using psql or python? Error!


    I'm retrieving some fields using psql, sort it and then display it in python, I have some problem, and my query's something like this :

    "select blah blah, round(sum(something)) from somewhere group by blah blah order by round(sum(something));"

    And when I display the result, something's not quite right, the results're not sorted in order, it showed something similar to this :

    result
    -------
    100.00
    101.10
    106.3
    105.5
    ...

    As you can see, some are in order, and some not, what seems to be the problem?

    I tried not to use order by and sort the results using list sorting in python, and the outcome is the same.
    What can change the nature of a man?
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    They are being sorted as strings. If you convert the values to numeric and then sort, the order will be as you expect.

    Note that the floating point numbers will not preserve well after the conversion - so you may need to do some formatting back to strings:
    Code:
    >>> a = ['100.00','101.10','106.3','105.5']
    >>> a
    ['100.00', '101.10', '106.3', '105.5']
    >>> c = map(float,a)
    >>> c
    [100.0, 101.09999999999999, 106.3, 105.5]
    >>> c.sort()
    >>> c
    [100.0, 101.09999999999999, 105.5, 106.3]
    >>>
    Grim
    Last edited by Grim Archon; March 31st, 2004 at 01:11 AM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Posts
    89
    Rep Power
    13
    are you sorting them using your MySQL query or are you using Python to sort them? if you're using MySQL, check to make sure that it's grouping them correctly before Python prints them out.

IMN logo majestic logo threadwatch logo seochat tools logo