2017-10-21 54 views
-6

我有一個由1或0組成的整數列表y。例如,在列表中隨機選擇值1並獲得索引

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

我想在列表中y它等於1隨機選擇兩個值,並獲得在列表中這些項目的指標。例如,

index = [0,5] 
+0

酷故事兄弟。 –

+0

嗨@scutnex,請使用[mcve] –

回答

2

選項1 - 推薦@StefanPochmann@rayryeng@Clayton Wahlstrom

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

選項2 - 我原來的可怕實現...

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

學習'枚舉'的時間。 –

+1

你可以用一個理解來代替循環:'index = [i for(i,j)in enumerate(y)if j == 1]'。 – rayryeng

+1

@rayryeng另一個改進,只要列舉的條件'如果j' –

0
  1. 使用enumerate創建包含項目的索引中y即等於1,只保留指數的新名單。
    ones = [i for i, elem in enumerate(y) if elem == 1]
  2. 使用random.sample隨機從這個新的列表中選擇的項目,在你的情況下,使用K = 2個樣品:
    sample_ones = random.sample(ones, k=2)

sample_ones是包含指數在隨機選擇的元素的列表y等於1.