0

I have a list predictions [0, 1, 0 , ....] and a list outcome [ 0, 0, 1, ...]. I want to create a list of all predictions where outcome is 1

I tried:

filtered_list = [predictions[i] for i in predictions if outcome[i]==1]

Unfortunately that resulted in an empty list.

What am I doing wrong? EDIT: I think I fixed it - not sure, as I have not been able to audit the result

filtered_list = [i for i in predictions if outcome[i]==1]
1
  • This does not fix it. Since predictions is a list of 0s and 1s, you are only looking at outcome[0] and outcome[1], not the outcome of a prediction. Commented Jun 5, 2020 at 21:02

3 Answers 3

1

If predictions and outcomes are of the same length, you can use zip()

[prediction for prediction, outcome in zip(predictions, outcome) if outcome==1]

Otherwise, just change zip() for the function zip_longest() of the itertools module.

Sign up to request clarification or add additional context in comments.

Comments

1

Use enumerate:

[i for c,i in enumerate(predictions) if outcome[c]==1]

Right now you are indexing by the values and not the indices and that is why it is not working

Comments

1

i is an actual prediction, not an index. You need to iterate over the indices to use i with both lists.

# Working, but meh. See below
filtered_list = [predictions[i] for i in range(len(predictions))
                  if outcome[i] == 1]

However, a better solution is to iterate over the elements of both lists in parallel, avoiding indices altogether.

filtered_list = [pred for pred, outcome in zip(predictions, outcomes) 
                  if outcome == 1]

Comments

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.