这篇文章我们介绍Python3中一个比较简单的模块,random模块,顾名思义:是生成随机数的一个模块;
言归正传,下面将对random中的常见函数进行讲解:
(1)、random():无参数,随机生成浮点数,区间为(0,1]
示例:print(random.random())
输出:0.8959623450106021
(2)、randint(start,stop):两个参数,随机生成[start,stop]区间内的整数
示例:print(random.randint(1,3))
输出:1
(3)、randrange(start,stop,step):返回指定递增基数集合中的一个随机数
示例:print(random.randrange(100,1000,2))
输出:694
(4)、uniform(start,stop):填补random()的缺陷,可以设置两个参数,下限和上限
示例:print(random.uniform(1,2))
输出:1.7134851989113074
(5)、choice(series):从序列中返回一个任意的元素,可以用于series为字符串、列表、元组
示例:print(random.choice([1,2,3,4,5,6]))
输出:4
(6)、shuffle(series):将序列的所有元素打乱
示例:list=[1,2,3,4,5]
print(list)
random.shuffle(list)
print(list)
输出:[1, 2, 3, 4, 5]
[2, 1, 3, 4, 5]
(7)、sample(series,num):两个参数,从序列中返回任意num个元素
示例:list1=[2,3,4,5,6,7,8]
print(random..sample(list1,5))
输出:[6, 4, 5, 2, 8]
典型例子
>>> random() # 随机浮点数: 0.0 <= x < 1.0
0.37444887175646646
>>> uniform(2.5, 10.0) # 随机浮点数: 2.5 <= x < 10.0
3.1800146073117523
>>> randrange(10) # 0-9的整数:
7
>>> randrange(0, 101, 2) # 0-100的偶数
26
>>> choice(['win', 'lose', 'draw']) # 从序列随机选择一个元素
'draw'
>>> deck = 'ace two three four'.split()
>>> shuffle(deck) # 对序列进行洗牌,改变原序列
>>> deck
['four', 'two', 'ace', 'three']
>>> sample([10, 20, 30, 40, 50], k=4) # 不改变原序列的抽取指定数目样本,并生成新序列
[40, 10, 50, 30]
>>> # 6次旋转红黑绿轮盘(带权重可重复的取样),不破坏原序列
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']
>>> # 德州扑克计算概率Deal 20 cards without replacement from a deck of 52 playing cards
>>> # and determine the proportion of cards with a ten-value
>>> # (a ten, jack, queen, or king).
>>> deck = collections.Counter(tens=16, low_cards=36)
>>> seen = sample(list(deck.elements()), k=20)
>>> seen.count('tens') / 20
0.15
>>> # 模拟概率Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> trial = lambda: choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
>>> sum(trial() for i in range(10000)) / 10000
0.4169
>>> # Probability of the median of 5 samples being in middle two quartiles
>>> trial = lambda : 2500 <= sorted(choices(range(10000), k=5))[2] < 7500
>>> sum(trial() for i in range(10000)) / 10000
0.7958
下面是生成一个包含大写字母A-Z和数字0-9的随机4位验证码的程序
import random
checkcode = ''
for i in range(4):
current = random.randrange(0,4)
if current != i:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print(checkcode)
下面是生成指定长度字母数字随机序列的代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random, string
def gen_random_string(length):
# 数字的个数随机产生
num_of_numeric = random.randint(1,length-1)
# 剩下的都是字母
num_of_letter = length - num_of_numeric
# 随机生成数字
numerics = [random.choice(string.digits) for i in range(num_of_numeric)]
# 随机生成字母
letters = [random.choice(string.ascii_letters) for i in range(num_of_letter)]
# 结合两者
all_chars = numerics + letters
# 洗牌
random.shuffle(all_chars)
# 生成最终字符串
result = ''.join([i for i in all_chars])
return result
if __name__ == '__main__':
print(gen_random_string(64))