Reputation: 1551
I have a list like
my_id = 3
Word IDs: [None, 0, 1, 2, 3, 3, 3, 4, None]
I want to make a list of all indexes in the above list that their corresponding value is equal to my_id
I want to write a one-line for loop. This is not working. Is there some way to write it as a "one-line for loop"?
My way:
list_of_word_ids = [i for enumerate(i,_id) in inputs if _id == id_word ]
My desired outputs in this case are
4, 5, 6
Upvotes: 2
Views: 2229
Reputation: 878
A one-liner would be numpy:
np.where(np.array(Word_IDs) == 3)[0].tolist()
and the result:
[4, 5, 6]
Upvotes: 2
Reputation:
enumerate
returns a tuple with its counter. You can unpack the tuple and check if seconds value is equal to my_id
Word_IDs= [None, 0, 1, 2, 3, 3, 3, 4, None]
list_of_word_ids = [i for i,j in enumerate(Word_IDs) if j == my_id]
Upvotes: 4