【发布时间】:2017-06-13 00:22:58
【问题描述】:
我正在使用随机数生成器从列表中随机选择一个问题,如果该问题已被回答,它应该跳过并重新滚动,直到它得到一个尚未给出的数字。
它一直有效,直到选项变得太有限。它会滚动〜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。 -
您要查找的术语是“shuffle”。使用
random.shuffle,然后弹出项目。 -
random.randint()包括两个端点。所以有时你会得到最后一点:超出范围。使用randrange(),或者,更好地检查上面的cmets是否真的是pythonic。 -
顺便说一句,不要使用
list作为变量名:这会影响内置的list类型。有时它可能工作正常,但有时它可能会导致产生神秘错误消息的错误。此外,使用循环来获取列表的大小是非常低效的。只需使用len()函数即可。