sorting items in a table problematic because of scientific notation

skip at pobox.com skip at pobox.com
Wed Apr 29 02:04:14 CEST 2009


    Amélie> Hi All,

    Amélie> I have a dbf table outputted by another program that I cannot
    Amélie> (I'm pretty sure) change the format of.

    Amélie> I use a dbf reader code found online
    Amélie> (http://code.activestate.com/recipes/362715/ ) to read the table
    Amélie> in and I need to sort it on a particular field but this field
    Amélie> has scientific notation in it and when I use the following
    Amélie> command, it seems to ignore the scientific notation which is
    Amélie> very problematic outlist = sorted(records, key=itemgetter(2)) .

You should convert numeric fields to floats or ints as appropriate.  It
appears the dbf reader isn't converting the numbers in scientific notation
to floats because they contain leading spaces, e.g.:

    [53, 55, ' 1.05646365517e+005']

You can make a pass through your list of lists and strip the whitespace:

    >>> s = ' 1.05646365517e+005'
    >>> float(s.strip())
    105646.365517

-- 
Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/
        "XML sucks, dictionaries rock" - Dave Beazley



More information about the Python-list mailing list