python 中random模块的常用方法总结

yipeiwu_com6年前Python基础

python 中random的常用方法总结

一、random常用模块

1.random.random() 随机生成一个小数

print(random.random())
 
# 输出
0.6060562117996784

2.random.randint(m,n) 随机生成一个m到n的整数(包括n)

print(random.randint(1, 5))
 
#输出
 
5

3. random.randrange(m,n) 随机生成m到n中的一个数,包括 m 但是不包括 n

print(random.randrange(1, 5))
 
# 输出
 
3

4. random.smaple(source,n) 在 source 中随机找出n个值,生成一个列表

print(random.sample(range(100), 5))
 
#输出
[27, 49, 21, 81, 45]

二、string 模块

 2.1 string.ascii_letters   # 所有的大小写英文字母

letters = string.ascii_letters
print(letters)
 
# 输出
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

2.2 string.ascii_lowercase # 所有的小写字母

2.3 string.ascii_uppercase # 所有的大写字母

2.4 string.digit # 1-9

2.5 string.punctuation  #特殊字符

sss = string.punctuation
print(sss)
 
# 输出
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
  

2.6 生成一个随机验证码

我们利用random和string模块模拟生成一个包含特殊字符以及大小写的验证码

import random
import string
 
str_source = {
 1: string.ascii_lowercase,
 2: string.ascii_uppercase,
 3: string.digits,
 4: string.punctuation
}
 
check = []
 
for i in range(1, 5):
  y = random.sample(str_source[i], 1)
  check.append(y[0])
 
print("".join(check))
 
# 输出
bV5-

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Python编程实现及时获取新邮件的方法示例

本文实例讲述了Python编程实现及时获取新邮件的方法。分享给大家供大家参考,具体如下: #-*- encoding: utf-8 -*- import sys import loc...

利用Python如何制作好玩的GIF动图详解

利用Python如何制作好玩的GIF动图详解

前言 之前我们分享过用Python进行可视化的9种常见方式。其实我们还能让可视化图形逼格更高一些,今天就分享一下如何让可视化秀起来:用Python和matplotlib制作GIF图表。...

Python 类,property属性(简化属性的操作),@property,property()用法示例

本文实例讲述了Python 类,property属性(简化属性的操作),@property,property()用法。分享给大家供大家参考,具体如下: property属性的创建方式有两...

python如何制作缩略图

python如何制作缩略图

本文实例为大家分享了python制作缩略图的具体代码,供大家参考,具体内容如下 import cv2 #导入opencv模块 from tkinter import * #导入tki...

基于torch.where和布尔索引的速度比较

我就废话不多说了,直接上代码吧! import torch import time x = torch.Tensor([[1, 2, 3], [5, 5, 5], [7, 8, 9]...