Python_常用的随机数获取方式(待补充)

版权声明:本文为博主原创文章,转载请注明原文链接 https://blog.csdn.net/sailist/article/details/79997993

import random

取值

random.randint(0,5)#包括边界

一定范围内满足某个规则的整数

random.randrange(20,35,3) #表明是20/23/26/29.../35之中的整数

一定范围内的浮点数

random.random()*base #范围为[0,1),扩大范围乘相应的基数即可
random.uniform(0, 20) #或者使用这个

按概率获取一定数量的某几个数字

waiting…


挑选

打乱list元素

list_number = [1, 2, 3, 4, 5]
random.shuffle(list_number)

随机从list中选择一个

list_string = ['a', 'b', 'c', 'd', 'e']
random.choice(list_string)

从list中随机选择n个

random.sample([1,2,4,6,2],2) #第二个参数长度为list长度时候相当于shuffle

猜你喜欢

转载自blog.csdn.net/sailist/article/details/79997993