RNG应该忽略已经给出的数字[Python]

时间:2017-01-27 10:36:20

标签: python random generator

我使用随机数生成器从列表中随机选择一个问题,如果问题已经被回答,它应该跳过并重新滚动,直到它得到一个尚未给出的数字。

在选项变得太有限之前一直有效。它会滚动~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

我不知道自己做错了什么,请帮助。

谢谢:)

1 个答案:

答案 0 :(得分:1)

解决方案可能更简单,你实际上并不需要你的计数器。

我们假设你有一个问题清单:

import random
questions = ['how are you ?', 'happy now ?', 'Another question ?']

然后您将打印其中一个问题:

question = random.choice(foo)
print question

然后从列表中删除它:

# del questions[questions.index(question)]
questions.remove(question)

你走了! ;)