0

I have this code:

a = [12, 3, 4, 6, 7, 13, 21]
label = [1, 1, 1, 0, 1, 1, 0] 
print([float(i) for i in a if label[i] == 1])

I just want to return the index of label which is 1, and then the index used for a to search a new list, so the result should be [12, 3, 4, 7, 13].

Can I write this in one line? Now my code problem is on i, I know it returns the item of a, not an index, how can I solve it?

0

3 Answers 3

2

i is not really index for label, you can use zip to loop through a and label in parallel, and pick a if label is 1:

[i for i, l in zip(a, label) if l == 1]
# [12, 3, 4, 7, 13]
Sign up to request clarification or add additional context in comments.

Comments

2

With enumerate, you can access both values and counters within list comprehension.

[a[i] for i, v in enumerate(label) if v == 1]
#[12, 3, 4, 7, 13]

Comments

1

You can convert the lists into numpy array and use boolean indexing

import numpy as np

a = np.array([12,3,4,6,7,13,21])
label = np.array([1,1,1,0,1,1,0])

print(a[label == 1])
>> [12  3  4  7 13]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.