import random
#生成随机的整数
print(random.randint(1,100))
print(random.randint(1,101,2))
print(random.randint(2,100,2))
# 生成随机数的浮点数
print(random.random())
print(random.uniform(11.1,13.1))
#非数字类型的随机抽样
targetList = [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘]
print(random.choice(targetList))
#乱序
print(random.shuffle(targetList))
print(random.sample(targetList, 4))#随机抽取4个作为子类
举个例子~
#生成随机密码字符串
import random
import string
def gen_random_string(length):
numcount = random.randint(1,length-1)
lettercount = length - numcount
numlist = [random.choice(string.digits) for i in range (numcount)]
letterlist = [random.choice(string.ascii_letters) for _ in range(lettercount)]
alllist = random.shuffle(numlist + letterlist)
result = "".join([i for i in alllist])
return result
原文:https://www.cnblogs.com/kangshuaibo/p/14810582.html