gsamaras gsamaras - 1 month ago 5x
Python Question

Towards understanding One Line For loops

After reading this question, I have this PySpark code:

model = KMeansModel(model.Cs[0])
first_split = x: x[0])
model = KMeansModel(model.Cs[1])
second_split = x: x[1])

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?


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( 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( 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 x: x[0]).