random模块
想使用 先导包
import random
random()
随机生成一个 大于0且小于1的浮点数
randint(start,stop)
# 源码
def randint(self, a, b):
"""Return random integer in range [a, b], including both end points.
返回范围[a,b]中的随机整数,包括两个端点
"""
choice(seq)
# 源码
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
从非空序列中选择一个随机元素
shuffle(seq)
# 源码
def shuffle(self, x, random=None):
"""Shuffle list x in place, and return None.
将列表x随机排序,然后返回无
Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.
"""
randrange(start, stop[, step])
# 源码
def randrange(self, start, stop=None, step=1, _int=int):
"""Choose a random item from range(start, stop[, step]).
从范围中选择一个随机项目(start, stop[, step])
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
"""
返回一个区间的随机整数,并且可以指定步长(不指定默认为1)
以1, 2, 3, 4, 5, 6, 7, 8, 9, 10举例:
random.randrange(1,10,2) #1-10之间 步长为2,适合的有1, 3, 5, 7, 9
sample(population, k)
# 源码
def sample(self, population, k):
"""Chooses k unique random elements from a population sequence or set.
# 从总体序列或集合中选择k个唯一的随机元素
uniform(a, b)
# 源码
def uniform(self, a, b):
"Get a random number in the range [a, b) or [a, b] depending on rounding."
# 根据四舍五入,在[a,b)或[a,b]范围内获取一个随机数
return a + (b-a) * self.random()