List/Conditional Comprehension in Python
<p>I was wondering how to make the following into a comprehension:</p>

<pre><code>for g in a:
    for f in g[::3]:
        if f == clf.best_params_:
            print g
</code></pre>

<p>I tried this:</p>

<pre><code>p = [[print g for g in a] if f==clf.best_params for f in [g[::3] for g in a]]
p
</code></pre>

<p>but got an error at <code>for f in</code> </p>

<p>Would love some help! Thanks!</p>

<p><strong>Rule 1</strong> - Keep the order of the <code>for</code> and <code>if</code> parts the same. The only part that changes order is the last part, <code>print g</code>: that moves to the front.</p>

<pre><code>[print g for g in a for f in g[::3] if f == clf.best_params_]
</code></pre>

<p><strong>Rule 2</strong> - List comprehensions should not <em>do</em> anything. Instead of <em>printing</em> <code>g</code>, have <code>g</code> be the value that is accumulated.</p>

<pre><code>[g for g in a for f in g[::3] if f == clf.best_params_]
</code></pre>

<p>If your entire goal was simply to print things, stick with the original loops; a list comprehension wouldn't add any value.</p>

<hr>

<p>If we take another look at your original nested loops, there may be a better way to write them. Is your goal to find all the items <code>g</code> that have <code>clf.best_params_</code> in one of the matching positions? If so, I recommend replacing the inner loop with a single <code>if any</code> statement.</p>

<pre><code>for g in a:
    if any(f == clf.best_params_ for f in g[::3]):
        print g
</code></pre>

<p>To me, this reads better. The logic is clearer. It will only print any one value of <code>g</code> once, instead of multiple times if <code>clf.best_params_</code> is present more than once.</p>

<p>If that is an improvement, then you could convert that version to a list comprehension like so:</p>

<pre><code>[g for g in a if any(f == clf.best_params_ for f in g[::3])]
</code></pre>

python list scikit-learn conditional list-comprehension