Loop and the list

Peter Otten __peter__ at web.de
Fri May 14 12:14:23 EDT 2004


Krzysztof Szynter wrote:

> def normowanie(TY,max):
>     "normalize the function"
>     for i in range(0,len(TY)-1):
>         TY[i] = TY[i]/float(TY[max])
>     return TY

While you iterate over TY, for i==max TY[max] suddenly changes to 1, and now
all further items are divided by 1, i. e. remain unchanged.

Remove the second argument altogether, remove your maxvalue() function and
then put the following line at the beginning of your script:

from __future__ import division # indicate that we want 
                                # 1/2 == 0.5 instead of 0

Now the revised normalization function (untested):

def normowanie(TY):
    m = max(TY) 
    return [v/m for v in TY]

This creates a normalized copy of the original list. You can call it:

normalizedTY = normowanie(TY)

If you want to change TY in place, i. e. you need not keep the original
list, here's that variant:

def normowanie(TY):
    m = max(TY)
    TY[:] = [v/m for v in TY]

As this follows the example of the mutating methods like list.append() and
list.sort() and doesn't return the list, call it like so:

normowanie(TY)

All items in TY are now in the range 0 <= v <= 1 (assuming there were no
negative values in the first place), but the original values are lost.

Peter




More information about the Python-list mailing list