sorting items in a table problematic because of scientific notation

MRAB google at mrabarnett.plus.com
Tue Apr 28 20:18:08 EDT 2009


skip at pobox.com wrote:
>     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
> 
FYI:

 >>> float(s)
105646.365517

which saves a few keystrokes. :-)



More information about the Python-list mailing list