Towards understanding One Line For loops
<p>After reading <a href="http://stackoverflow.com/questions/12920214/python-for-syntax-block-code-vs-single-line-generator-expressions">this</a> question, I have this PySpark code:</p>

<pre><code>model = KMeansModel(model.Cs[0])
first_split = split_vecs.map(lambda x: x[0])
model.computeCost(first_split)
model = KMeansModel(model.Cs[1])
second_split = split_vecs.map(lambda x: x[1])
model.computeCost(second_split)
</code></pre>

<p>Can I write this into a one-liner for loop? Or these loops are restricted in having <em>only one</em> line in their body?</p>

<p>Note: I am not looking for code-only answers, I want to learn, so please, explain. :)</p>

<hr>

<p>Here is my tragic attempt:</p>

<pre><code>model.computeCost(split) for i in range(2): # &lt;- the semicolon here doesn't feel right..Where to put the other lines?
</code></pre>

<hr>

<p>Edit:</p>

<p>Yes, I know that I can write a regular <a href="/questions/tagged/for-loop" class="post-tag" title="show questions tagged &#39;for-loop&#39;" rel="tag">for-loop</a>, but I would like to understand one-liner for loops. This is for experimenting. You see, when reading others' people code, I see them often, and I am not comfortable with them... :/</p>

<p>This is untested, but it looks like it could work for you</p>

<pre><code>computedCost = [KMeansModel(model.Cs[i]).computeCost(x[i]) for i in xrange(2)]
</code></pre>

<p>What it does is create a list of results after performing computeCost() on the results of <code>KMeansModel()</code>.  the <code>xrange for loop</code> just returns the values for i</p>

python loops for-loop apache-spark pyspark