基于random库,编写了几种生成随机数的方法,包括生成指定数量的随机数字,生成随机字符串,生成英文+数字随机字符串,生成指定范围的随机数列表(可设置允不允许重复),生成指定范围的小数(可设置小数位位数)
import random
import string
class RandomTool:
def __init__(self):
self.en_chars = string.ascii_letters
self.digit_chars = string.digits
self.mark_chars = '@#$%^&*(){}_+=:"<>?|\【】[],();:;~“”·?、|——-¥!'
def createSomeDigit(self,n=6):
digit_list = random.sample(self.digit_chars,n)
random_digit = "".join('%s' % i for i in digit_list)
return random_digit
def createSomeStr(self,n=6):
source = self.digit_chars + self.en_chars + self.mark_chars
str_list = random.sample(source,n)
return ''.join(str_list)
def createSomeLetterDigit(self,n=6):
source = self.digit_chars + self.en_chars
str_list = random.sample(source, n)
return ''.join(str_list)
def createSomeNums(self,least,largest,n=6,allowRepeat=True):
if n == 1:
return random.randint(least,largest)
num_list = []
while 1:
if allowRepeat:
num_list.append(random.randint(least,largest))
if len(num_list) == n:
break
else:
randNum = random.randint(least,largest)
if randNum not in num_list:
num_list.append(randNum)
if len(num_list) == n:
break
return num_list
def createSomeDecimal(self,least,largest,n=4):
decimals = random.uniform(least,largest)
if n:
return round(decimals,n)
return decimals
下面是使用
randTool = RandomTool()
rand_result1 = randTool.createSomeDigit(5)
print('结果1:',rand_result1)
rand_result2 = randTool.createSomeStr(5)
print('结果2:',rand_result2)
rand_result3 = randTool.createSomeLetterDigit(5)
print('结果3:',rand_result3)
rand_result4 = randTool.createSomeNums(5,100,10,allowRepeat=False)
print('结果4:',rand_result4)
rand_result5 = randTool.createSomeDecimal(100,120,3)
print('结果5:',rand_result5)
——————————————————————————————————————————————
运行结果:
结果1: 32457
结果2: hD{KS
结果3: XSI0p
结果4: [53, 12, 76, 21, 85, 56, 5, 66, 25, 61]
结果5: 115.485
目前可生成上述五种随机数,可根据自身需要再进一步修改调整。