Python random.sample-giving';样本大于总体或为阴性';当样本长度与总体长度相同时

Python random.sample-giving';样本大于总体或为阴性';当样本长度与总体长度相同时,python,Python,如果我的总体中的项目数等于我想要的样本数,我会得到错误 这里有一个最小的例子 import random subset = random.sample( set([312996, 529565, 312996, 130934]) , 4) --------------------------------------------------------------------------- ValueError Traceback

如果我的总体中的项目数等于我想要的样本数,我会得到错误

这里有一个最小的例子

import random

subset = random.sample( set([312996, 529565, 312996, 130934]) ,  4)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-b816cd5c3651> in <module>()
----> 1 subset = random.sample( set([312996, 529565, 312996, 130934]) ,  4)

/opt/conda/lib/python3.6/random.py in sample(self, population, k)
    318         n = len(population)
    319         if not 0 <= k <= n:
--> 320             raise ValueError("Sample larger than population or is negative")
    321         result = [None] * k
    322         setsize = 21        # size of a small set minus size of an empty list

ValueError: Sample larger than population or is negative

我没有出错。我不知道第一个问题是什么

问题在于
集合([3129961529565312996130934])
只有3个元素

s = set([312996, 529565, 312996, 130934])

for element in s:
    print(element)
输出

312996
529565
130934
[130934, 312996, 529565]
集合只有唯一的元素,因此函数
set()
将删除重复的元素
312996
。在第二个示例中,
集合([2,5,8,9])
有4个不同的元素。可以通过以下方式避免错误:

import random

s = {312996, 529565, 312996, 130934}
subset = random.sample(s, min(len(s), 4))

print(subset)
输出

312996
529565
130934
[130934, 312996, 529565]
这样可以确保采样的元素不会超过集合中的元素数