1. random.random
random.random()用于生成一个0到1之间的随机浮点数:0<=n<1
>>> random.random()
0.7086588033796296
2. random.uniform
random.uniform(a,b)用于生成一个指定范围内的随机浮点数,若a<b,则a<=n<=b;若a>b,则b<=n<=a.
>>> random.uniform(12,5)
6.128208009182529
>>> random.uniform(5,12)
5.373996230739382
>>> random.uniform(5,5)
5.0
3. random.randint
random.randint(a,b)用于生成一个指定范围内的整数:a<=n<=b;下限必须小于等于上限值,random.randint(20,10)是错误的
>>> random.randint(10,10)
10
>>> random.randint(10,21)
15
>>> random.randint(100,100)
100
4. random.randrange
random.randrange([start],[stop],[step])从指定范围内,按指定基数递增的集合中获取一个随机数。等于random.choice(range([start],[stop],[step]))
>>> random.randrange(1,100,10)
61
>>> random.randrange(1,100,10)
21
>>> random.choice(range(1,100,10))
71
>>> random.choice(range(1,100,10))
41
>>> random.randrange(100,100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/random.py", line 199, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (100,100, 0)
5. random.choice
random.choice(seq)从序列中获取随机一个元素。
choices(population, weights=None, *, cum_weights=None, k=1)这个方法平时比较少用,population是一个可迭代对象,weights是相对权重,cum_weights是累积权重,k表示随机获取的个数。
例如,相对权重``[10, 5, 30, 5]``相当于累积权重``[10, 15, 45, 50]``。 在内部,相对权重在进行选择之前会转换为累积权重,因此提供累积权重可以节省工作量。random官方文档
需要注意2点:
1. weights和cum_weights不能同时使用。
2.population与weights,population与cum_weights需一一对应
>>> random.choice("abcde")
'd'
>>> random.choice([1,2,3,4])
2
>>> random.choice((1.1,2.2,3.3,4.4))
3.3
>>> for i in range(10):
... print(random.choices("abcd",weights=[1,1,7,1],cum_weights=[70,10,5,15],k=1))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "E:\Programs\Python36\lib\random.py", line 356, in choices
raise TypeError('Cannot specify both weights and cumulative weights')
TypeError: Cannot specify both weights and cumulative weights
>>> for i in range(10):
... print(random.choices(['x','y','z'],cum_weights=[70,10,5,15],k=1))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "E:\Programs\Python36\lib\random.py", line 358, in choices
raise ValueError('The number of weights does not match the population')
ValueError: The number of weights does not match the population
>>> for i in range(10):
... print(random.choices(['x','y','z','u'],cum_weights=[70,10,5],k=1))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "E:\Programs\Python36\lib\random.py", line 358, in choices
raise ValueError('The number of weights does not match the population')
ValueError: The number of weights does not match the population
>>> for i in range(10):
... print(random.choices("abcd",weights=[1,1,7,1],k=1))
...
['b']
['c']
['c']
['c']
['c']
['c']
['a']
['a']
['c']
['c']
由上可以明显发现,随机获得c的概率更高
>>> for i in range(10):
... print(random.choices(['x','y','z','w'],cum_weights=[70,10,5,15],k=1))
...
['w']
['w']
['w']
['w']
['x']
['x']
['w']
['x']
['x']
['x']
6. random.shuffle
random.shuffle(x[, random])用于将一个列表中的元素打乱
>>> l=['a','b','c','d','e']
>>> random.shuffle(l)
>>> l
['d', 'b', 'e', 'c', 'a']
7. random.sample
random.sample(seq,k)从指定序列中随机获取指定长度的,且不重复出现的片段
>>> l=['a','b','c','d','e']
>>> s=random.sample(l,2)
>>> s
['c', 'a']
>>> l
['a', 'b', 'c', 'd', 'e']
8. random.seed
random.seed(n)用于改变随机数生成器的种子,指定随机数生成时所用的算法。
>>> random.seed(2)
>>> random.random()
0.9560342718892494
>>> random.random()
0.9478274870593494
9. 实践
写一个函数:随机生成n个整数,n个整数的和等于m
import random
def random_num(n, m):
# 随机生成n个数字
numbers = [random.random() for _ in range(n)]
# 计算出 m 与 n个随机数的商
k = m / sum(numbers)
# n个随机数分别乘以k,n个数的和接近于m
result = [int(i * k) for i in numbers]
# 从result中随机选择一个数,加上m与sum(result)的差数,从而实现sum(result) = m
result[random.randint(0,n-1)] += m - sum(result)
print("sum(result)=", sum(result))
print("result=", result)
>>> random_num(5, 100)
sum(result)= 100
result= [5, 21, 15, 33, 26]
>>> random_num(2, 15)
sum(result)= 15
result= [2, 13]
>>>