random模块

random模块

  • 定义:随机生成整数 / 小数 / 指定列表值某个元素

【一】随机生成小数

【1】默认区间的小数 区间0-1之间的小数

复制代码
import random
print(random.random())      # 0.5858839340258046

【2】指定区间 给定区间内的小数

复制代码
import random
print(random.uniform(4,8 ))     # 7.467665328012298

【二】随机生成整数

【1】指定区间的整数 给定区间内的整数

复制代码
import random
print(random.randint(1,10))     # 8

【2】随机区间内的奇偶数

复制代码
import random
print(random.randrange(1,20,2))     # 1,3,5
print(random.randrange(1,20,3))     # 2,4,6

【三】随机返回值

【1】返回一个元素

先创建一个可迭代类型

复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choice(num_list))      # 输出abc 或者数字

【2】一次性返回多个元素

(1)以列表的形式返回结果
复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choices(num_list))     # [4]
(2)以指定关键字 k 指定返回列表中的元素个数
复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choices(num_list, k=3))    # ['c', 4, 1]
print(random.choices(num_list, 3))      # 与上面一条命令结果一样,默认值就是k

【四】打乱顺序

random.shuffle()

复制代码
num_list = [i for i in range(1,10)]
print(num_list)             # [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(num_list)    # 打乱顺序
print(num_list)         # [2, 3, 1, 8, 6, 5, 4, 7, 9]
​

【五】随机生成验证码

  • 随机大小写字母 + 随机数字

  • chr(数字) ---> 返回指定ASCII码对应的字符

  • 做一个能生成6位的验证码

复制代码
import random

def v_code(n):
    code=''
    for i in range(n):
        random_int = str(random.randint(0, 9))      # 0~9之间的整数
        random_upper = chr(random.randint(65,90))   # A~Z的大写字母
        random_lower = chr(random.randint(97,122))  # a~z的小写字母
        temp = random.choice([random_int, random_upper, random_lower])
        code += temp
    return code

result = v_code(6)
print(result)
相关推荐
海天一色y38 分钟前
Pycharm(十六)面向对象进阶
ide·python·pycharm
??? Meggie39 分钟前
【Python】保持Selenium稳定爬取的方法(防检测策略)
开发语言·python·selenium
XIE3922 小时前
Browser-use使用教程
python
酷爱码3 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼3 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
蹦蹦跳跳真可爱5893 小时前
Python----深度学习(基于深度学习Pytroch簇分类,圆环分类,月牙分类)
人工智能·pytorch·python·深度学习·分类
喵先生!4 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ4 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
xMathematics5 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
MinggeQingchun6 小时前
Python - 爬虫-网页解析数据-库lxml(支持XPath)
爬虫·python·xpath·lxml