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) to high (exclusive).

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐