python的random函数
更多的random用法可参阅:
random --- 生成伪随机数 - Python 3.7.4 文档docs.python.org以下使用了:
洗牌:random.shuffle
随机抽取元素,且元素不重复:random.sample
随机抽取元素,且元素可重复:random.choices
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 20:37:54 2019@author: wmnldora
"""import random
#从一组20个元素的列表里
dataMat=[]
for i in range(20):dataMat.append(i)#随机抽取5个元素
number=5 #打乱顺序
def RandomShuffle(dataMat):try:random.shuffle(dataMat)print(dataMat)return dataMatexcept:print("others")#随机抽取的元素不重复
def RandomSampling(dataMat,number):try:slice=random.sample(dataMat,number)print(slice)return sliceexcept:print("other")#随机抽取的元素可以重复
def RandomChoice(dataMat,number):try:slicec=random.choices(dataMat,k=number)print(slicec)return slicecexcept:print("other")#随机抽泣的元素可重复,普通写法
def RepetitionRandomSampling(dataMat,number):sample=[]for i in range(number):sample.append(dataMat[random.randint(0,len(dataMat)-1)])print(sample)return sample