擅长:python、mysql、java
<p>如果我能正确理解你的问题,这应该行得通:</p>
<pre><code>def weighted_sample(L, x):
# might consider raising some kind of exception of len(set(L)) < x
while True:
ans = random.sample(L, x)
if len(set(ans)) == x:
return ans
</code></pre>
<p>如果你想要很多这样的样品,你可以做如下的事情:</p>
<pre><code>[weighted_sample(L, x) for _ in range(num_samples)]
</code></pre>
<p>我很难想象对抽样逻辑的理解不仅仅是模糊的。逻辑有点太复杂了。对我来说,这听起来像是一个随机的附加在家庭作业上的东西。</p>
<p>如果你不喜欢无限循环,我还没有试过,但我认为这是可行的:</p>
<pre><code>def weighted_sample(L, x):
ans = []
c = collections.Counter(L)
while len(ans) < x:
r = random.randint(0, sum(c.values())
for k in c:
if r < c[k]:
ans.append(k)
del c[k]
break
else:
r -= c[k]
else:
# maybe throw an exception since this should never happen on valid input
return ans
</code></pre>