Python:random模块

1. random.random()

random.random()用于生成一个0到1之间的随机浮点数:0<=n<=1

import random

a = random.random()

print(a)

# result

0.7086588033796296

2. random.uniform(a, b)

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(a, b)

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表示随机获取的个数。

需要注意2点:

  • weights和cum_weights不能同时使用。
  • 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])用于将一个列表中的元素打乱

import random

L=[1,2,3,4,5,6,7]
random.shuffle(L)

print(L)

#运行结果[6, 7, 2, 5, 3, 4, 1]

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]
>>>

参考:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值