【问题标题】:RNG should ignore numers that have already been given [Python]RNG 应该忽略已经给出的数字 [Python]
【发布时间】: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() 函数即可。

标签: python random generator


【解决方案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)

给你! ;)

【讨论】:

  • 使用随机播放比删除列表中的项目更有效,因为当您删除除最后一项之外的任何项目时,所有后续项目都必须向下移动。当然,这个操作很快,因为它以 C 速度发生,但如果你真的不需要它,这样做仍然很浪费。此外,questions.index(question) 必须对列表执行线性扫描才能找到项目。
  • del questions[questions.index(question)]questions.remove(question)
  • @PM2Ring 我不明白为什么使用 shuffle 会更好?实际上,我们需要选择一个不必再问的问题。因此,即使使用shuffle,我们也必须选择一个问题,然后将其从原始列表中删除。
  • @iFlo 我们不需要删除任何内容。我们洗牌一次,在循环外,然后我们只遍历洗牌的列表。
  • 按照 iFlow 所说的去做。它有效,所以我很高兴。仍在学习python,所以感谢您的帮助。考虑到所有的解决方案。看看什么效果最好。
猜你喜欢
  • 2019-02-28
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多