gsamaras - 3 months ago 8
Python Question

Towards understanding One Line For loops

After reading this question, I have this PySpark 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)
``````

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

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

Here is my tragic attempt:

``````model.computeCost(split) for i in range(2): # <- the semicolon here doesn't feel right..Where to put the other lines?
``````

Edit:

Yes, I know I can write a regular , 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... :/

A list comprehension version of what you did in that example would be:

``````[KMeansModel(model.Cs[i]).computeCost(split_vecs.map(lambda x: x[i])) for i in range(2)]
``````

This is no different than:

``````results = []
for i in range(2):
results.append(KMeansModel(model.Cs[i]).computeCost(split_vecs.map(lambda x: x[i])))
``````

So for each `i`, it appends the returning value of that chained expression to the list. For this example, it happened to work because your three lines could be chained together. You are calling `computeCost()` method on the object you created with `KMeansModel(model.Cs[0])` and the parameter for that is `split_vecs.map(lambda x: x[0])`.

Source (Stackoverflow)