0

I need to convert a nested for loop with a function call and appending data to a list comprehension.

This is what I would like to convert to a list comprehension

predictions = []
for train_row in test_data:
    distances = np.argmin([dist(train_row, test_row) for test_row in train_data])
    predictions.append(train_tgt[distances])
2
  • Like this? predictions = [train_tgt[np.argmin([euclideanDistance(train_row, test_row) for test_row in train_data])] for train_row in test_data] Commented Jan 29, 2020 at 21:49
  • @Lapis Rose Thank you !!! it works Commented Jan 29, 2020 at 22:07

1 Answer 1

1

On the surface, it's a trivial transformation after inlining the definition of distances:

predictions = []
for train_row in test_data:
    distances = ...
    predictions.append(train_tgt[distances])

becomes

predictions = []
for train_row in test_data:
    predictions.append(train_tgt[...])

which becomes

predictions = [train_tgt[...] for train_row in test_data]
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for breaking it down. I just need to continue the statement with one of the loops

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.