Python random模块
Python random模块
random模块
用于生成随机数
import random
print(random.random())
print(random.randint(1, 100))
print(random.randrange(1,100))
输出结果:
0.18246795790915304
46
66
randint和randrange的区别
##########randint##########
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
"""
return self.randrange(a, b+1)
##########randrange##########
def randrange(self, start, stop=None, step=1, _int=int):
"""Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
"""
# This code is a bit messy to make it fast for the
# common case while still doing adequate error checking.
istart = _int(start)
if istart != start:
raise ValueError("non-integer arg 1 for randrange()")
if stop is None:
if istart > 0:
return self._randbelow(istart)
raise ValueError("empty range for randrange()")
# stop argument supplied.
istop = _int(stop)
if istop != stop:
raise ValueError("non-integer stop for randrange()")
width = istop - istart
if step == 1 and width > 0:
return istart + self._randbelow(width)
if step == 1:
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
# Non-unit step argument supplied.
istep = _int(step)
if istep != step:
raise ValueError("non-integer step for randrange()")
if istep > 0:
n = (width + istep - 1) // istep
elif istep < 0:
n = (width + istep + 1) // istep
else:
raise ValueError("zero step for randrange()")
if n <= 0:
raise ValueError("empty range for randrange()")
return istart + istep*self._randbelow(n)
常用的 random 模块方法
import random
# random.random()用于生成一个 0 到 1 的随机浮点数: 0 <= n < 1.0
print(random.random()) # 0.18246795790915304
# random.randint(a, b),用于生成一个指定范围内的整数。
# 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print(random.randint(1, 10)) # 8
# random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中获取一个随机数
# 如:random.randrang(10, 100, 2),结果相当于从[10,12,14,16, ... 96,98]序列中选取一个随机数
# random.randrang(10, 100, 2) 在结果上与 random.choice(range(10,100,2)) 等效
print(random.randrange(1,10)) # 5
# random.choice 从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。
print(random.choice("Python")) # y
print(random.choice(["JGood", "is", "a", "handsome", "boy"])) # JGood
print(random.choice(("Tuple", "List", "Dict"))) # List
# random.sample(sequence, k),从指定序列中随机获取指定长度的片段。sample函数不会修改原有序列。
print(random.sample([1,2,3,4,5],3)) #[1,2,5]
# random.shuffle(x[, random]),用于将一个列表中的元素打乱。
p = ["Python", "is", "powerful", "simple", "and so on..."]
print(random.shuffle(p))
# ['powerful', 'simple', 'is', 'Python', 'and so on...']
# random.uniform(a, b),用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。
# 如果 a < b,则生成的随机数n: b >= n >= a
# 如果 a > b,则生成的随机数n: a >= n >= b
print random.uniform(10, 20) # 14.73
print random.uniform(20, 10) # 18.579
实际应用
import random
# 随机生成浮点数
print(random.random()) #随机返回0~1之间的浮点数
0.47626693393991737
print(random.uniform(1,10)) #随机返回1~10之间的浮点数
4.0844448042717225
# 随机生成整数
print(random.randint(1,10)) #随机生成1~10之间的整数
8
print(random.randrange(0,10,2)) #随机生成0~10之间的偶数
8
print(random.randrange(1,10,2)) #随机生成1~10之间的基数
1
# 操作序列、字符串
lis = [1,2,3,4,5,6,7,8,9,10]
## 从序列、字符串中随机返回一个元素
print(random.choice(lis))
4
print(random.choice('abcdefg'))
g
## 随机截取序列、字符串中指定长度片段
print(random.sample(lis,2))
[9, 4]
print(random.sample('abcdefg',2))
['f', 'a']
## 打乱一个序列
random.shuffle(lis)
print(lis)
[7, 6, 1, 2, 10, 3, 4, 8, 5, 9]
生成随机验证码
import random
checkcode = ''
for i in range(6):
current = random.randrange(0, 6)
if current != i:
temp = chr(random.randint(65, 90))
else:
temp = random.randint(0, 9)
checkcode += str(temp)
print(checkcode)
输入结果:
7DWLGY