Kadaj13
Kadaj13

Reputation: 1551

Using enumerate for "one-line for loops"

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

Answers (2)

Rm4n
Rm4n

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

user15801675
user15801675

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

Related Questions