<p>您可以使用<a href="http://docs.python.org/2/library/random.html#random.sample" rel="noreferrer">^{<cd1>}</a>:</p>
<pre><code>>>> random.sample(xrange(1,50), 6)
[26, 39, 36, 46, 37, 1]
</code></pre>
<hr/>
<blockquote>
<p><em>"The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help."</em></p>
</blockquote>
<p>假设这是一个赋值,并且您需要自己实现采样,那么您可以<a href="http://hg.python.org/cpython/file/efedd0f62a7e/Lib/random.py#l268" rel="noreferrer">take a look at how ^{<cd1>} is implemented</a>。它确实很有用,但是对于您的需要来说可能太复杂了,因为代码还确保了所有子切片也是有效的随机样本。为了提高效率,它还根据人口规模采用不同的方法。</p>
<p>至于工作表,我认为它假定您从1到49的数字列表开始,并建议您用0替换您选择的数字,以便在重新选择时可以跳过。这里有一些伪代码让您开始:</p>
<pre>
population = range(1, 50) # list of numbers from 1 to 49
sample = []
until we get 6 samples:
index = a random number from 0 to 48 # look up random.randint()
if population[index] is not 0: # if we found an unmarked value
append population[index] to sample
set population[index] = 0 # mark selected
</pre>
<p>如果你想尝试一些不同的方法,有很多其他的方法可以考虑,例如随机列表然后截断,或者某种形式的<a href="http://en.wikipedia.org/wiki/Reservoir_sampling" rel="noreferrer">reservoir sampling</a>。</p>
<p>祝你的作业顺利。</p>