<p>如果将答案选项加载到容器中,则可以将Python的<code>random</code>(<a href="https://docs.python.org/2/library/random.html" rel="nofollow">link</a>)库与以下一个或两个工具一起使用:</p>
<ul>
<li><code>random.choice(seq)</code>(<a href="https://docs.python.org/2/library/random.html#random.choice" rel="nofollow">link</a>),它随机选择<code>seq</code>中提供的可能项</li>
<li><code>random.sample(pop, k)</code>(<a href="https://docs.python.org/2/library/random.html#random.sample" rel="nofollow">link</a>)哪个选项<code>k</code>从<code>pop</code>中提供的可能选择中唯一的元素,<em>而不替换</em>,我认为这在您的情况下很关键,因为您不希望在同一个问题上显示相同的答案两次。在</li>
</ul>
<p>这将简化当前if语句块,从</p>
<pre><code>if randomnumber == 0:
layout.addWidget(self.Correctanswer)
layout.addWidget(self.Incorrectans1)
layout.addWidget(self.Incorrectans2)
layout.addWidget(self.Incorrectans3)
</code></pre>
<p>到</p>
^{pr2}$
<p>又想到了另一个很酷的主意。如果你有一个很大的“池”可能的错误答案,你可以定义一个函数来提供随机选择的错误答案。比如:</p>
<pre><code>def provideWrongAnswers(self, number):
return random.sample(self.allWrongAnswersPool, number)
</code></pre>
<p>这将为您提供<code>number</code>个不正确的答案,并将其添加到布局中。在</p>
<pre><code>In [7]: choices = range(1,11)
In [9]: random.sample(choices, 3) # returns a different order of choices each time
Out[9]: [1, 7, 3]
In [10]: random.sample(choices, 3)
Out[10]: [6, 9, 3]
In [11]: random.sample(choices, 3)
Out[11]: [5, 4, 2]
In [12]: random.sample(choices, 3)
Out[12]: [3, 6, 1]
In [13]: random.sample(choices, 3)
Out[13]: [10, 8, 3]
In [14]: random.sample(choices, 3)
Out[14]: [1, 7, 2]
In [15]: random.sample(choices, 3)
Out[15]: [9, 7, 3]
</code></pre>
<p>最后,<code>random.shuffle(x)</code>(<a href="https://docs.python.org/2/library/random.html#random.shuffle" rel="nofollow">link</a>)是另一种方法,因为它采用序列<code>x</code>并将它们混合在一起。所以你可以把<code>random.sample(wrongChoices, 3)</code>的想法结合起来,随机给出三个不正确的答案,然后加上正确的答案,确保正确的答案并不总是在底部,用<code>random.shuffle(allAnswerChoices)</code>给他们最后一次搅拌</p>