• Python零基础入门-11 标准库简介 —— 第二部分


    11. 标准库简介 —— 第二部分

    11.1. 格式化输出

    reprlib 模块提供了一个定制化版本的 repr() 函数,用于缩略显示大型或深层嵌套的容器对象

    pprint 模块提供了更加复杂的打印控制,其输出的内置对象和用户自定义对象能够被解释器直接读取。当输出结果过长而需要折行时,“美化输出机制”会添加换行符和缩进,以更清楚地展示数据结构。

    textwrap 模块能够格式化文本段落,以适应给定的屏幕宽度。

    locale 模块处理与特定地域文化相关的数据格式。locale 模块的 format 函数包含一个 grouping 属性,可直接将数字格式化为带有组分隔符的样式。

    11.2. 模板

    string 模块包含一个通用的 Template 类,具有适用于最终用户的简化语法。它允许用户在不更改应用逻辑的情况下定制自己的应用。

    11.3. 使用二进制数据记录格式

    11.4. 多线程

    线程是一种对于非顺序依赖的多个任务进行解耦的技术。多线程可以提高应用的响应效率,当接收用户输入的同时,保持其他任务在后台运行。一个有关的应用场景是,将 I/O 和计算运行在两个并行的线程中。

    以下代码展示了高阶的 threading 模块如何在后台运行任务,且不影响主程序的继续运行:

    import threading, zipfile
    
    class AsyncZip(threading.Thread):
        def __init__(self, infile, outfile):
            threading.Thread.__init__(self)
            self.infile = infile
            self.outfile = outfile
    
        def run(self):
            f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
            f.write(self.infile)
            f.close()
            print('Finished background zip of:', self.infile)
    
    background = AsyncZip('mydata.txt', 'myarchive.zip')
    background.start()
    print('The main program continues to run in foreground.')
    
    background.join()    # Wait for the background task to finish
    print('Main program waited until background was done.')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    11.5. 日志记录

    logging 模块提供功能齐全且灵活的日志记录系统。在最简单的情况下,日志消息被发送到文件或 sys.stderr

    import logging
    logging.debug('Debugging information')
    logging.info('Informational message')
    logging.warning('Warning:config file %s not found', 'server.conf')
    logging.error('Error occurred')
    logging.critical('Critical error -- shutting down')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这会产生以下输出:

    WARNING:root:Warning:config file server.conf not found
    ERROR:root:Error occurred
    CRITICAL:root:Critical error -- shutting down
    
    • 1
    • 2
    • 3

    默认情况下,informational 和 debugging 消息被压制,输出会发送到标准错误流。其他输出选项包括将消息转发到电子邮件,数据报,套接字或 HTTP 服务器。新的过滤器可以根据消息优先级选择不同的路由方式:DEBUGINFOWARNINGERROR,和 CRITICAL

    日志系统可以直接从 Python 配置,也可以从用户配置文件加载,以便自定义日志记录而无需更改应用程序。

    11.6. 弱引用

    weakref 模块

    11.7. 用于操作列表的工具

    array 模块提供了一种 array() 对象,它类似于列表,但只能存储类型一致的数据且存储密集更高。 下面的例子演示了一个以两个字节为存储单元的无符号二进制数值的数组 (类型码为 "H"),而对于普通列表来说,每个条目存储为标准 Python 的 int 对象通常要占用16 个字节:

    >>> from array import array
    >>> a = array('H', [4000, 10, 700, 22222])
    >>> sum(a)
    26932
    >>> a[1:3]
    array('H', [10, 700])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    collections 模块提供了一种 deque()对象,它类似于列表,但从左端添加和弹出的速度较快,而在中间查找的速度较慢。 此种对象适用于实现队列和广度优先树搜索:

    >>> from collections import deque
    >>> d = deque(["task1", "task2", "task3"])
    >>> d.append("task4")
    >>> print("Handling", d.popleft())
    Handling task1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    unsearched = deque([starting_node])
    def breadth_first_search(unsearched):
        node = unsearched.popleft()
        for m in gen_moves(node):
            if is_goal(m):
                return m
            unsearched.append(m)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在替代的列表实现以外,标准库也提供了其他工具,例如 bisect 模块具有用于操作有序列表的函数:

    >>> import bisect
    >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
    >>> bisect.insort(scores, (300, 'ruby'))
    >>> scores
    [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
    
    • 1
    • 2
    • 3
    • 4
    • 5

    heapq 模块提供了基于常规列表来实现堆的函数。 最小值的条目总是保持在位置零。 这对于需要重复访问最小元素而不希望运行完整列表排序的应用来说非常有用:

    >>> from heapq import heapify, heappop, heappush
    >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
    >>> heapify(data)                      # rearrange the list into heap order
    >>> heappush(data, -5)                 # add a new entry
    >>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
    [-5, 0, 1]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    11.8. 十进制浮点运算

    decimal 模块提供了一种 Decimal 数据类型用于十进制浮点运算。 相比内置的 float 二进制浮点实现,该类特别适用于

    • 财务应用和其他需要精确十进制表示的用途,

    • 控制精度,

    • 控制四舍五入以满足法律或监管要求,

    • 跟踪有效小数位,

    • 用户期望结果与手工完成的计算相匹配的应用程序。

    例如,对70美分话费计算5%税,使用十进制浮点和二进制浮点数计算,会产生的不同结果。如果结果四舍五入到最接近的分数差异会明显:

    >>> from decimal import *
    >>> round(Decimal('0.70') * Decimal('1.05'), 2)
    Decimal('0.74')
    >>> round(.70 * 1.05, 2)
    0.73
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Decimal 表示的结果会保留尾部的零,并根据具有两个有效位的被乘数自动推出四个有效位。 Decimal 可以模拟手工运算来避免当二进制浮点数无法精确表示十进制数时会导致的问题。

    精确表示特性使得 Decimal 类能够执行对于二进制浮点数来说不适用的模运算和相等性检测:

    >>> Decimal('1.00') % Decimal('.10')
    Decimal('0.00')
    >>> 1.00 % 0.10
    0.09999999999999995
    
    >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
    True
    >>> sum([0.1]*10) == 1.0
    False
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    decimal 模块提供了运算所需要的足够精度:

    >>> getcontext().prec = 36
    >>> Decimal(1) / Decimal(7)
    Decimal('0.142857142857142857142857142857142857')
    
    • 1
    • 2
    • 3
  • 相关阅读:
    uniapp使用pinia状态管理永久缓存方法
    3.Vue从入门到精通 (第三章 使用Vue脚手架)
    山东大学单片机原理与应用实验 3.7LCD 1602显示实验
    洛谷刷题C语言:陶瓷项链、Cow Gymnastics B、Where Am I? B、Hello, 2020!、SIR 模型
    pytest + yaml 框架 -4.用例参数化parameters功能实现
    K8S学习笔记
    【思考】我为钱工作 OR 钱为我工作?
    开源机器人SmallRobotArm机器人源码解读
    【Linux学习笔记】 - 常用指令学习及其验证(上)
    TCP握手为什么是三次?两次行不行?
  • 原文地址:https://blog.csdn.net/qq_41068877/article/details/125556214