Python模块之random

from random import *

1、生成浮点随机数

生成的浮点数数值在(a,b)之

uniform(10,10)
10.0
uniform(1,10)
6.727523452496653
uniform(10,1)
4.774701548091901
uniform(10,10)
10.0
uniform(10,10)
10.0

 uniform(1,10.1)
 8.10015246791915

2、生成整数随机数

randint(1,1)
1
randint(1,10)
3
randint(10,1)#报错
randint(1,10.1)#报错

3、生成随机偶数

randrange(10,100,2)
76
randrange(10,100,2)
44

4、生成随机字符(参数内的)

#单个字符
choice('asas121') 's' choice('asas121^%^$') '^'
#字符集

 choice([123,'abc','1a2b'])
 'abc'
 choice([123,'abc','1a2b'])
 123

 

5、生成指定数目的随机字符(参数内)

sample('asas121^%^$',2)
['%', '2']
sample('asas121^%^$',2)
['s', '$']

6、对列表元素进行随机重新组合

l = [1,2,3,4,'s']
shuffle(l)
l
[4, 's', 2, 1, 3]

附:

生成固定位随机字符,可用来当密钥
import os
os.urandom(12)
'}x89xf1yxb7{xd3*e1yZ'
os.urandom(24)
'xf8Vx94VRt={kx1c{xfcxe4xb4xe2Ex9fx1exfdxddMcx0fm'
原文地址:https://www.cnblogs.com/dyzne/p/7207689.html