Simple list question

Dave Brueck dave at pythonapocrypha.com
Fri Jan 30 17:00:26 CET 2004


C GIllespie wrote:
> I have a list something like this: ['1','+','2'], I went to go through and
> change the numbers to floats, e.g. [1,'+',2]. What's the best way of doing
> this? The way I done it seems wrong, e.g.
> 
> nod=['1','+','2']
> i=0
> while i<len(nod):
>     if nod[i] !='+' or nod[i] !='-' or nod[i]!='*' or nod[i] != '/' or
> nod[i] != '(' or nod[i] != ')':
>         nod[i] = float(nod[i])
>     i = i + 1

How about:

>>> nod = ['1','+','2']
>>> for i in range(len(nod)):
...   try:
...     nod[i] = float(nod[i])
...   except ValueError: pass
...
>>> nod
[1.0, '+', 2.0]

-Dave




More information about the Python-list mailing list