Simple list question

Peter Otten __peter__ at web.de
Fri Jan 30 11:31:06 EST 2004


C GIllespie wrote:

> Dear all,
> 
> 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

If you really want the [1,'+',2] format, use int() instead of float(). 

> 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
> 
> Comments?

Nothing is wrong with the above, although a  for loop is more common.

for i in range(len(nod)):
  # ...

Instead of testing for all non-floats, you could just try to convert the
list item, keeping it unchanged if an error occurs. Here's a full example
using enumerate() instead of range():

>>> nod = ["1", "+", "2"]
>>> for i, v in enumerate(nod):
...     try:
...             v = float(v)
...     except ValueError:
...             pass
...     else: # yes, try...except has an else (=no exception) branch, too
...             nod[i] = v
...
>>> nod
[1.0, '+', 2.0]

Peter




More information about the Python-list mailing list