Minimum and Maximum of a list containing floating point numbers

Tim Chase python.list at tim.thechases.com
Mon Sep 6 21:00:39 EDT 2010


On 09/06/10 19:37, ceycey wrote:
> I have a list like ['1.1881', '1.1881', '1.1881', '1.1881', '1.1881',
> '1.1881', '1.1881', '1.1881', '1.1881', '1.1881', '1.7689',  '1.7689',
> '3.4225', '7.7284', '10.24', '9.0601', '9.0601', '9.0601', '9.0601',
> '9.0601']. What I want to do is to find minimum  and maximum number in
> this list.
>
> I used min function,
>
> print min(s)
> print max(s)
>
> these gives me
>
> 1.181
> 9.0601
>
> maximum value is wrong. It must be 10.24.
>
> I know why max function gives wrong number. Because max function
> processed elements of list as strings. How can I convert the elements
> of list to float so max function finds the correct answer.

You can use

   min(float(v) for v in s)
   max(float(v) for v in s)

to return the floating-point number, or in Python2.5+ you can use

   min(s, key=float)
   max(s, key=float)

to get the string source.  If you need the source string in 
pre-2.5, you'd have to do something like

   min((float(v), v) for v in s)[1]   # 2.4
   min([(float(v), v) for v in s])[1] # 2.3 or earlier

and guard against empty input lists.

-tkc







More information about the Python-list mailing list