1、随机抽取一个元素
from random import choice
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(choice(l)) # 随机抽取一个
可能的一种输出:
3
对 choice(seq)
的解释:
Choose a random element from a non-empty sequence.
2、随机抽取若干个元素(无重复)
from random import sample
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(sample(l, 5)) # 随机抽取5个元素
可能的一种输出:
[8, 3, 4, 9, 10]
对 sample(population, k)
的解释:
Chooses k unique random elements from a population sequence or set.
3、随机抽取若干个元素(有重复)
import numpy as np
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
idxs = np.random.randint(0, len(l), size=5) # 生成长度为5的随机数组,范围为 [0,10),作为索引
print([l[i] for i in idxs]) # 按照索引,去l中获取到对应的值
可能的一种输出:
[8, 8, 7, 4, 1]
对 randint(low, high=None, size=None, dtype='l')
的解释:
Return random integers from
low
(inclusive) tohigh
(exclusive).