Python的random模块
来源:互联网 发布:58淘宝运营学徒骗局 编辑:程序博客网 时间:2024/06/08 19:06
【Python模块学习】3、random模块
参考:1、官网;2、别人的
以下是random模块的方法:
实例:
Basic examples:
>>> random() # 随机浮点数: 0.0 <= x < 1.00.37444887175646646>>> uniform(2.5, 10.0) # 随机浮点数: 2.5 <= x < 10.03.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次旋转红黑绿轮盘(带权重可重复的取样),不破坏原序列,weight[18,18,2]>>> 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') / 200.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.'H'的概率是0.6,“T”的概率是1-0.6>>> trial = lambda: choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5>>> sum(trial() for i in range(10000)) / 100000.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)) / 100000.7958>>> from statistics import mean>>> from random import choices>>> data = 1, 2, 4, 4, 10>>> means = sorted(mean(choices(data, k=5)) for i in range(20)) # mean是求平均>>> print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' f'interval from {means[1]:.1f} to {means[-2]:.1f}') # 这里的f用法
下面是生成一个包含大写字母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)
下面是生成指定长度字母数字随机序列的代码:
阅读全文
0 0
- python的 random模块
- Python的random模块
- Python的random模块
- python的np.random模块
- 10、Python 的random模块
- 【python系列】经常用到的random模块
- python:与概率有关的random模块
- python中numpy的random模块
- Python的numpy.random模块中文简介
- Python random模块
- Python中的random模块
- Python 之 random模块
- python模块之----random
- python random模块
- python random模块
- Python random模块
- python random模块
- Python random模块
- 面向对象的概念
- Python3之yeild监听器应用
- Hello,World
- 博客不见了
- 集合学习笔记
- Python的random模块
- HashMap原理
- 新手玩CSS中的一些黑科技
- Java线程:什么是线程
- Java线程:线程中断
- Java线程:线程状态
- STM32移植systick定时器时出现错物error:#20:identifier"IRQn_Type"isundefined
- Java线程: 线程调度
- Java线程:同步