Python编程:random随机模块

简介: Python编程:random随机模块

订阅专栏

内置函数
import random
# 随机小数[0, 1)
print(random.random())  # 0.8121215001773937
# 随机小数[a, b),指定区间
print(random.uniform(1,5))  # 3.2253060854754354
# 数据整数[a, b]
print(random.randint(1,5))  # 3
# 随机范围,取偶数
print(random.randrange(0,50,2))  # 14
# 随机取值string
print(random.choice("python")) # n
# 随机取值list
lst = ["one", "two", "three"]
print(random.choice(lst))  # one
# 随机取值tuple
tp = ("one", "two", "three")
print(random.choice(tp))  # two
# 取样
print(random.sample("abcdefg", 3))
# ['e', 'g', 'c']
# 洗牌
lst = [1, 2, 3, 4, 5,6]
random.shuffle(lst)
print(lst)  # [3, 2, 1, 6, 5, 4]

生成四位随机验证码

# 方案一:
checkcode = ""
for i in range(4):
    current = random.randrange(0,4)
    # 生成字母
    if i == current:
        tmp = chr(random.randint(65, 90)) #  A - Z
    # 生成数字
    else:
        tmp = str(random.randint(0,9))
    checkcode += tmp
print(checkcode)  # 715C


# 方案二:
import string
codes = string.ascii_letters + string.digits
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
sample = random.sample(codes, 4)  # ['c', 'l', 'p', '5']
check_code = "".join(sample)
print(check_code)  # clp5

help(random)

FUNCTIONS
    choice(seq) method of Random instance
        Choose a random element from a non-empty sequence.    
    randint(a, b) method of Random instance
        Return random integer in range [a, b], including both end points.
    random(...) method of Random instance
        random() -> x in the interval [0, 1).
    randrange(start, stop=None, step=1, _int=<class 'int'>) method of Random instance
        Choose a random item from range(start, stop[, step]).
        This fixes the problem with randint() which includes the
        endpoint; in Python this is usually not what you want.
    sample(population, k) method of Random instance
        Chooses k unique random elements from a population sequence or set.
        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).
        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.
        To choose a sample in a range of integers, use range as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(range(10000000), 60)
    seed(a=None, version=2) method of Random instance
        Initialize internal state from hashable object.
        None or no argument seeds from current time or from an operating
        system specific randomness source if available.
        For version 2 (the default), all of the bits are used if *a* is a str,
        bytes, or bytearray.  For version 1, the hash() of *a* is used instead.
        If *a* is an int, all bits are used.
    shuffle(x, random=None) method of Random instance
        Shuffle list x in place, and return None.
        Optional argument random is a 0-argument function returning a
        random float in [0.0, 1.0); if it is the default None, the
        standard random.random will be used.
    uniform(a, b) method of Random instance
        Get a random number in the range [a, b) or [a, b] depending on rounding.
相关文章
|
2月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
314 7
|
2月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
236 0
|
2月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
181 3
|
2月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
438 3
|
2月前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
366 4
|
2月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
267 3
|
2月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
271 0
|
2月前
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
182 0
|
3月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
288 0
|
算法 安全 量子技术
【Python】蒙特卡洛模拟 | PRNG 伪随机数发生器 | 马特赛特旋转算法 | LCG 线性同余算法 | Python Random 模块
【Python】蒙特卡洛模拟 | PRNG 伪随机数发生器 | 马特赛特旋转算法 | LCG 线性同余算法 | Python Random 模块
812 0

推荐镜像

更多