Loading

随机选择与打乱

1. 随机选择

使用random包

从列表里随机选出一个元素
from random import choice
ls = [1, 2, 3, 4]
print(choice(ls))

2. 随机抽样

从列表里随机抽出出一组元素,不放回抽样
import random
ls = [1, 2, 3, 4]
c = random.sample(ls, 3)  # 从list中随机获取5个元素,作为一个片断返回
print(c)

np.random.choice(a, size=10, replace=True) # 放回抽样
从列表里随机抽出出一组元素,放回抽样
import numpy as np
ls = [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中获取到对应的值

3.打乱操作

# 打乱并返回列表
ls = np.random.permutation(ls)
# 直接将原数组打乱,不返回
random.shuffle(ls)
np.random.shuffle(ls)

posted @ 2021-05-25 12:41  Guang'Jun  阅读(134)  评论(0编辑  收藏  举报