# 扣丁学堂浅谈Python视频教程之random模块详解

random.seed(a=None, version=2)

random.getstate()

random.setstate(state)

random.getrandbits(k)

random.randrange(stop)

random.randrange(start, stop[, step])

random.randint(a, b)

random.choice(seq)

random.choices(population, weights=None, *, cum_weights=None, k=1)

3.6版本新增。从population集群中随机抽取K个元素。weights是相对权重列表，cum_weights是累计权重，两个参数不能同时存在。

random.shuffle(x[, random])

random.sample(population, k)

random模块最高端的功能其实在这里。

random.random()

random.uniform(a, b)

random.triangular(low, high, mode)

random.betavariate(alpha, beta)

β分布。返回的结果在0~1之间

random.expovariate(lambd)

random.gammavariate(alpha, beta)

random.gauss(mu, sigma)

random.lognormvariate(mu, sigma)

random.normalvariate(mu, sigma)

random.vonmisesvariate(mu, kappa)

random.paretovariate(alpha)

random.weibullvariate(alpha, beta)

class random.SystemRandom([seed])

>>> random() # 随机浮点数: 0.0

>>> uniform(2.5, 10.0) # 随机浮点数: 2.5

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

>>> sum(trial() for i in range(10000)) / 10000

0.7958

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

774 篇文章97 人订阅

0 条评论

## 相关文章

34390

3.3K40

31140

### 函数玩一玩 | 【SAS Says·扩展篇】IML：2.函数

【SAS Says·扩展篇】IML 分6集，回复【SASIML】查看全部： 入门 | SAS里的平行世界 函数 | 函数玩一玩 编程 | IML的条件与循环 模...

38890

25770

26220

48650

### keras doc 7 Pooling Connceted Recurrent Embedding Activation

‘th’模式下，为形如（samples，channels, rows，cols）的4D张量

14230

### 【干货】计算机视觉实战系列03——用Python做图像处理

【导读】专知成员Hui上一次为大家介绍Matplotlib的使用，包括绘图，绘制点和线，以及图像的轮廓和直方图，这一次为大家详细讲解Numpy工具包中的各种工具...

479100

30130