Simple list question

Stefan Axelsson sax at csmisc72.cs.chalmers.se
Fri Jan 30 17:36:15 CET 2004


In article <mailman.1047.1075478440.12720.python-list at python.org>, Dave Brueck wrote:
> 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]

Perhaps minor style issue; I'd use 'map' (even though Guido isn't
crazy about it), or perhaps a list comprehension.

Like so:

>>> def tofloat(x):
...     try:
...             return float(x)
...     except ValueError: return x
...

>>> map(tofloat, nod)
[1.0, '+', 2.0]

Stefan,
-- 
Stefan Axelsson                  (email at http://www.cs.chalmers.se/~sax)



More information about the Python-list mailing list