我使用隨機數生成器從隨機列表中選擇一個問題,如果問題已經被回答,它應該跳過並重新滾動,直到它得到一個數字還沒有給出。RNG應該忽略已經給出的分子[Python]
它的工作原理,直到選項變得太有限。它會滾動~4次。如果它還沒有一個以前沒有給出的數字,它會給出一個「索引超出範圍」的錯誤。
樣品:
from random import randint
counter = 0 # Max value, count the amount of questions in the list
done = [] # Already been rolled, ignore these values
list = open('questions.txt').readlines()
for l in list:
counter +=1
try:
# While there are less values in <done> than <counter>, roll and add to list
while len(done) < counter:
question = randint(1,counter)
while question in done:
print('Skipped [%i]' % question) # Check if ignored
question = randint(1,counter) # Reroll
else:
# Add to list so it knows the question has already been asked
done.append(question) # Add to list with given values
else:
print('Finished!\n')
except Exception as e:
print(e) # Show error if any
我不知道我做錯了,請幫助。
謝謝:)
順便說一下,你應該使用'random.sample'。 – TigerhawkT3
您正在尋找的術語是「洗牌」。使用'random.shuffle',然後關閉項目。 – jamesdlin
'random.randint()'包含兩個端點。所以有時你會得到最後一點:超出範圍。使用'randrange()',或者,更好地檢查上面的註釋是否真的pythonic。 –