PYTHON 从列表中随机化问题并枚举



我有一个包含 25 个问题的列表,我想随机选择 7 个。问题列表将在IRC客户端(文本)中。以下是我目前提出的问题以及我提议从列表中随机化 7 的过程的示例。

我想做

questions=[
    'Finish this poem "Roses are red Violets are ..."',
    'What is your favorite food?','Stones or Beatles?',
    'favorite pet?',
    'favorite color?',
    'favorite food?'
]
for q in xrange(3):
    question = ''
    while question not in questions:
        # this is where I'm stuck

我想要类似的东西。

  1. 你最喜欢的食物是什么?
  2. 最喜欢的宠物?
  3. 石头还是披头士?

最终结果将是 7 个问题中的 25 个问题。

您可以使用

shuffle()

from random import shuffle
shuffle(questions)
for question in questions[:7]:
    answer = input(question)
    # do something with answer

一个好的方法可以使用random.sample

>>> from random import sample
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
>>> selected = []
>>> for item in sample(items, 7):
...    selected.append(item)
>>> print selected
['h', 'l', 'j', 'm', 'i', 'e', 'c']

使用 random.sample()

import random
for question in random.sample(questions, 7):
    answer = input(question)

但是,您需要有足够的问题。 现在你只有六个问题在列表中,所以random.sample()无法提出七个随机问题。 我假设你的真实清单有 25 个问题,因为你说from a pool of 25,所以我只是评论。

最新更新