[Solved] Randomly select value 1 in list and get index


Option 1 – as recommended @StefanPochmann, @rayryeng and @Clayton Wahlstrom.

index = [i for (i, j) in enumerate(y) if j]
print(random.sample(index, 2))

Option 2 – My original horrible implementation…

import random

y = [1,0,0,0,0,1,0]

i = 0
index =[]
for each in y:
    if each == 1:
        index.append(i)
    i = i + 1
print(random.sample(index, 2))

3

solved Randomly select value 1 in list and get index