从列表arr中随机选择k个数据。选出的数据在arr中的位置不重复。k小于等于arr的长度
random.sample(arr,k)
import random
value = [1,2,3,4]
r = random.sample(value,4) ## 随机选出4个数
print(r)
r = random.sample(value,5) ## 报错
print(r)
当大于数组长度时,报错如下
raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
python 手册解释
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
(保证取出数据在列表中的位置不重复)
Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
To choose a sample from a range of integers, use a range() object as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), k=60).
If the sample size is larger than the population size, a ValueError is raised.
random.sample()是Python的一个函数,用于从给定列表或集合中不重复地随机抽取k个元素。如果k大于列表长度,会引发ValueError。这个函数常用于进行随机采样,且不影响原列表。当尝试从列表value中抽取大于其长度的元素时,程序会抛出ValueError错误。
954





