<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body bgcolor="#ffffff" text="#000000">
<tt>I'm new to this list, so please excuse me if this topic has been
discussed, but I didn't<br>
see anything similar in the archives.<br>
<br>
I very often want something like a try-except conditional expression
similar<br>
to the if-else conditional. <br>
<br>
An example of the proposed syntax might be:<br>
<font color="#6600cc"> x = float(string) except float('nan')<br>
</font>or possibly<br>
<font color="#6600cc"> x = float(string) except ValueError
float('nan')<br>
</font><br>
Here's a simple example: Converting a large list of strings to floats
where there may be errors<br>
that I want returned as nan's.<br>
<br>
Currently I would write the function:<br>
</tt><tt><font color="#6600cc"> def safe_float_function(string):<br>
try:<br>
result = float(string)<br>
except:<br>
result = float('nan')<br>
return result<br>
</font></tt><tt>and get my list of floats using the list comprehension:<br>
</tt><tt><font color="#6600cc"> xs = [ safe_float_function(string)
for string in strings ]<br>
<br>
</font></tt><tt>With a try-except conditional I would instead define
the following lambda:<br>
<font color="#6600cc"> safe_float_conditional = lambda string :
float(string) except float('nan')<br>
</font>leading to:<br>
</tt><tt><font color="#6600cc"> xs = [
safe_float_conditional(string) for string in strings ]<br>
</font></tt><br>
My understanding is that the second would be faster at run time, and,
like if-else conditional expressions, <br>
possibly more easily read by the human.<br>
<br>
Again, please excuse me if this has been discussed previously. If so,
I'd appreciate being pointed to the discussion.<br>
<br>
Please also excuse me if for there is some currently (pre-python 3.0)
idiom that I could use to efficiently get this<br>
same behaviour. If so, I'd appreciate being educated.<br>
<br>
Thanks,<br>
Jeff McAninch<br>
<pre class="moz-signature" cols="72">--
==========================
Jeffrey E. McAninch, PhD
Physicist, X-2-IFD
Los Alamos National Laboratory
Phone: 505-667-0374
Email: <a class="moz-txt-link-abbreviated" href="mailto:mcaninch@lanl.gov">mcaninch@lanl.gov</a>
==========================
</pre>
</body>
</html>