Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerate two lists at once
    primarykey
    data
    text
    <p><strong>Background</strong></p> <p>The algorithm manipulates financial analytics. There are multiple lists of the same size and they are filtered into other lists for analysis. I am doing the same filtering on different by parallel lists. I could set it up so that a1,b1,c2 occur as a tuple in a list but then the analytics have to stripe the tuples the other way to do analysis (regression of one list against the other, beta, etc.).</p> <p><strong>What I want to do</strong></p> <p>I want to generate two different lists based on a third list:</p> <pre><code>&gt;&gt;&gt; a = list(range(10)) &gt;&gt;&gt; b = list(range(10,20)) &gt;&gt;&gt; c = list(i &amp; 1 for i in range(10)) &gt;&gt;&gt; &gt;&gt;&gt; aprime = [a1 for a1, c1 in zip(a,c) if c1 == 0] &gt;&gt;&gt; bprime = [b1 for b1, c1 in zip(b,c) if c1 == 0] &gt;&gt;&gt; aprime [0, 2, 4, 6, 8] &gt;&gt;&gt; bprime [10, 12, 14, 16, 18] </code></pre> <p>It seems there should be a pythonic/functional programming/itertools way to create the two lists and iterate over the three lists only once. Something like:</p> <pre><code>aprime, bprime = [a1, b1 for a1, b1, c1 in zip(a,b,c) if c1 == 0] </code></pre> <p>But of course this generates a syntax error.</p> <p><strong>The question</strong></p> <p>Is there a pythonic way?</p> <p><strong>Micro-optimization shootout</strong></p> <p>The ugly but pythonic-to-the-max one-liner edges out the "just use a for-loop" solution and my original code in the ever popular <em>timeit</em> cage match:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn zip(*[(a1,b1) for a1,b1,c1 in zip(a,b,c) if c1==0])\n") 26.977873025761482 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\taprime, bprime = [], [];\n\tfor a1, b1, c1 in zip(a, b, c):\n\t\tif c1 == 0:\n\t\t\taprime.append(a1); bprime.append(b1);\n\treturn aprime, bprime\n") 32.232914169258947 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn [a1 for a1, c1 in zip(a,c) if c1 == 0], [b1 for b1, c1 in zip(b,c) if c1 == 0]\n") 32.37302275847901 </code></pre>
    singulars
    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.
 

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