擅长:python、mysql、java
<p>不要重新发明轮子。你要找的是<a href="https://docs.python.org/2/library/random.html#random.sample" rel="nofollow">^{<cd1>}</a>-</p>
<pre><code>>>> s=set(range(1,10))
>>> import random
>>> random.sample(s,7)
[7, 5, 6, 8, 9, 3, 4]
</code></pre>
<p>尽管处理<code>set</code>实际上看起来像是一个实现细节(可能不适用于超过21个元素的集合),因为<code>random.sample</code>在内部将它接收到的iterable(第一个参数)转换为<a href="https://hg.python.org/cpython/file/c6880edaf6f3/Lib/random.py#l330" rel="nofollow">https://hg.python.org/cpython/file/c6880edaf6f3/Lib/random.py#l330</a>处的列表。最好不要依赖此实现细节,而是手动将集合/序列转换为列表或序列-</p>
<pre><code>>>> s=set(range(1,10))
>>> import random
>>> random.sample(list(s),7)
[6, 8, 4, 2, 5, 9, 7]
</code></pre>
<p>根据文件-</p>
<blockquote>
<p><code>random.sample(population, k)</code></p>
<p>Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.</p>
</blockquote>
<p>正如在评论中提到的,您可能并不真正需要在这里设置。你知道吗</p>