<p>自Python 3.6以来,有一个来自<a href="https://docs.python.org/dev/library/random.html#module-random" rel="noreferrer">^{<cd2>}</a>模块的方法<a href="https://docs.python.org/dev/library/random.html#random.choices" rel="noreferrer">^{<cd1>}</a>。</p>
<pre><code>Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.0.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import random
In [2]: random.choices(
...: population=[['a','b'], ['b','a'], ['c','b']],
...: weights=[0.2, 0.2, 0.6],
...: k=10
...: )
Out[2]:
[['c', 'b'],
['c', 'b'],
['b', 'a'],
['c', 'b'],
['c', 'b'],
['b', 'a'],
['c', 'b'],
['b', 'a'],
['c', 'b'],
['c', 'b']]
</code></pre>
<p>注意,<code>random.choices</code>将根据<a href="https://docs.python.org/dev/library/random.html#random.choices" rel="noreferrer">docs</a>对<em>进行采样,并替换为</em>:</p>
<blockquote>
<p>Return a <code>k</code> sized list of elements chosen from the population with replacement.</p>
</blockquote>
<p>如果需要在不替换的情况下采样,那么作为<a href="https://stackoverflow.com/a/26196078/3124746">@ronan-paixão's brilliant answer</a>状态,可以使用<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html" rel="noreferrer">^{<cd4>}</a>,其<code>replace</code>参数控制这种行为。</p>