Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Edit: I have just realised I misread the question, and we are talking about a list of lists, not just a list. Updated to suit that.</p> <p>You can use a <a href="https://www.youtube.com/watch?v=t85uBptTDYY" rel="nofollow noreferrer">list comprehension</a> here to produce something a bit <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops" rel="nofollow noreferrer">faster</a> and nicer to read:</p> <pre><code>def to_float_or_None(x): try: return float(x) except ValueError: return None database = [["1", "1.0", "", "foobar", "3.0"], ["1", "1.0", "", "foobar", "3.0"]] result = [[to_float_or_None(item) for item in record] for record in database] </code></pre> <p>Giving us:</p> <pre><code>[[1.0, 1.0, None, None, 3.0], [1.0, 1.0, None, None, 3.0]] </code></pre> <p>Edit: As noted by <a href="https://stackoverflow.com/users/63011/paolo-moretti">Paolo Moretti</a> in the comments, if you want the absolute fastest result, then using <code>map</code> <a href="https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map">may be faster</a> as we are not using a lambda function:</p> <pre><code>def to_float_or_None(x): try: return float(x) except ValueError: return None database = [["1", "1.0", "", "foobar", "3.0"], ["1", "1.0", "", "foobar", "3.0"]] result = [list(map(to_float_or_None, record)) for record in database] </code></pre> <p>Giving us the same result. I would note, however, that premature optimization is a bad thing. If you have identified this as a bottleneck in your application, then fair enough, but otherwise stick with the more readable over the fast.</p> <p>We still use a list comprehension for the outer loop as we would need a lambda function to use <code>map</code> again given it's dependence on <code>record</code>:</p> <pre><code>result = map(lambda record: map(to_float_or_None, record), database) </code></pre> <p>Naturally, if you want to evaluate these lazily, you can use generator expressions:</p> <pre><code>((to_float_or_None(item) for item in record) for record in database) </code></pre> <p>Or:</p> <pre><code>(map(to_float_or_None, record) for record in database) </code></pre> <p>This would be the preferred method unless you need the entire list at once.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload