Note that there are some explanatory texts on larger screens.

plurals
  1. POList Comprehensions in Python : efficient selection in a list
    primarykey
    data
    text
    <p>Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a <em>distance</em> to an other element).</p> <p>I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code</p> <pre><code>result = [ ( myFunction(C), C) for C in originalList if myFunction(C) &lt; limit ] </code></pre> <p>But <code>myFunction</code> is a very time-consuming function, and the <code>originalList</code> quite big. So doing like that, <code>myFunction</code> will be call twice for every selected element.</p> <p>So, is there a way to avoid this ??</p> <p>I have two other possibilities, but they are not so good:</p> <ol> <li><p>the first one, is to create the unfiltered list</p> <pre><code>unfiltered = [ (myFunction(C),C) for C in originalList ] </code></pre> <p>and then sort it</p> <pre><code>result = [ (dist,C) for dist,C in unfiltered if dist &lt; limit ] </code></pre> <p>but in that case, I duplicate my <code>originalList</code> and waste some memory (the list could be quite big - more than 10,000 elements)</p></li> <li><p>the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). <code>myFunction</code> stores it last<br> result in a global variable (<code>lastResult</code> for example), and this value is re-used in the List comprehension </p> <pre><code>result = [ (lastResult,C) for C in originalList if myFunction(C) &lt; limit ] </code></pre></li> </ol> <p>Do you have any better idea to achieve that, in an efficient and pythonic way ??</p> <p>Thanks for your answers.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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