random随机数
random随机数
1.概述
random用来生成一些随机数,下面介绍random模块提供的方法根据需求生成不同的随机数。
2.random常用操作
2.1.random默认随机数
random()函数返回一个随机的浮点值,默认返回值范围在0 <= n < 1.0区间
import randomfor i in range(5):print('%04.3f' % random.random(), end=' ')
print()
运行结果
0.481 0.369 0.876 0.659 0.124
2.2.指定范围随机数
生成一个指定数值区间内的数,则要用uniform()
import randomfor i in range(5):print('{:04.3f}'.format(random.uniform(1, 100)), end=' ')
print()
运行结果
68.240 10.768 30.234 80.859 91.582
randrange()是从区间选择值的方式,可以指定开始值,结束值,步长。
randrange更高效,因为它并没有真正构造区间。
import randomfor i in range(3):print(random.randrange(0, 101, 5), end=' ')
print()
运行结果
90 15 50
2.3.指定种子
如果需要重复使用相同值的随机序列,random提供了seed函数,他可以生成一个期望的值集。seed参数可以使任意可散列对象。
例如第一次运行random生成了一系列的随机值,第二次运行希望使用第一次生成的值,通过设置相同的seed值,即可保持随机的值不变。
import randomrandom.seed(1)for i in range(5):print('{:04.3f}'.format(random.random()), end=' ')
print()
重复运行上面的代码,只要不改变seed值,它生成的随机值是一样的。
# 第一次运行
0.134 0.847 0.764 0.255 0.495
#第二次运行
0.134 0.847 0.764 0.255 0.495
2.4.随机整数
random将生成浮点数,可以把结果转换为整数,不过直接使用randint生成整数会更方便。
import randomprint('[1, 100]:', end=' ')for i in range(3):print(random.randint(1, 100), end=' ')print('\n[-5, 5]:', end=' ')
for i in range(3):print(random.randint(-5, 5), end=' ')
print()
运行代码,返回整数随机值
[1, 100]: 4 50 56
[-5, 5]: 4 -5 2
2.5.随机选择元素
random包含一个choice()函数,可以从随机序列中随机选择值。下面模拟一个抛硬币10 000次统计面朝上和面朝下次数。
import randomoutcomes = {'heads': 0,'tails': 0,
}
sides = list(outcomes.keys())for i in range(10000):outcomes[random.choice(sides)] += 1print('Heads:', outcomes['heads'])
print('Tails:', outcomes['tails'])
运行结果,统计了随机选择了硬币的次数。
Heads: 5055
Tails: 4945
2.6.排列
要模拟一个扑克牌游戏,需要把一副扑克牌混起来,然后发牌,同一张牌不能重复使用。可以用shuffle()洗牌,然后在发牌时删除所发的牌。
import random
import itertoolsFACE_CARDS = ('J', 'Q', 'K', 'A')
SUITS = ('H', 'D', 'C', 'S')def new_deck():return [# Always use 2 places for the value, so the strings# are a consistent width.'{:>2}{}'.format(*c)for c in itertools.product(itertools.chain(range(2, 11), FACE_CARDS),SUITS,)]def show_deck(deck):p_deck = deck[:]while p_deck:row = p_deck[:13]p_deck = p_deck[13:]for j in row:print(j, end=' ')print()# Make a new deck, with the cards in order
deck = new_deck()
print('Initial deck:')
show_deck(deck)# Shuffle the deck to randomize the order
random.shuffle(deck)
print('\nShuffled deck:')
show_deck(deck)# Deal 4 hands of 5 cards each
hands = [[], [], [], []]for i in range(5):for h in hands:h.append(deck.pop())# Show the hands
print('\nHands:')
for n, h in enumerate(hands):print('{}:'.format(n + 1), end=' ')for c in h:print(c, end=' ')print()# Show the remaining deck
print('\nRemaining deck:')
show_deck(deck)
2.7.不重复采样
有些时候生成的随机数可能会包含重复值,使用sample()函数可以从序列中随机取值保证值不重复。
from random import sample
data = [i for i in range(100)] # 列表推导式
result = sample(data, 10)
print(result)
运行上面的代码,sample从列表中随机取值,保证取到的值不重复
[86, 34, 56, 48, 21, 75, 79, 3, 57, 38]
2.8.并发生成随机数
random包括一个Random类,管理多个随机数状态,每个实例都可以单独使用互不干扰。
import random
import timeprint('Default initializiation:\n')r1 = random.Random()
r2 = random.Random()for i in range(3):print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))print('\nSame seed:\n')seed = time.time()
r1 = random.Random(seed)
r2 = random.Random(seed)for i in range(3):print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))
运行上面的代码,第二个使用了seed两个随机对象的值是相同的。
Default initializiation:0.666 0.946
0.080 0.385
0.315 0.768Same seed:0.112 0.112
0.657 0.657
0.064 0.064
2.9.系统随机
系统提供了一个随机数生成器,random通过SystemRandom类提供的功能,可以生成随机数。不过使用os.urandom()生成值,该值构成所有其他算法的基础。
SystemRandom产生的序列是不可再生的,来自于系统的随机性而不是软件状态,所以seed不再起作用。
import random
import timeprint('Default initializiation:\n')r1 = random.SystemRandom()
r2 = random.SystemRandom()for i in range(3):print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))print('\nSame seed:\n')seed = time.time()
r1 = random.SystemRandom(seed)
r2 = random.SystemRandom(seed)for i in range(3):print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))
运行代码,结果显示seed不再起作用。
Default initializiation:0.649 0.422
0.560 0.225
0.530 0.189Same seed:0.526 0.408
0.293 0.111
0.032 0.837