Python 3.7.x 介绍-8 标准库 2

Python 3.7.x 介绍-8 标准库 2

输出格式化

reprlib模块提供了一个版本的repr(),用于大型或深层嵌套容器的缩写显示:

>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"

textwrap模块格式化文本段落以适合给定的屏幕宽度

>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.

模板

字符串模块包括一个通用的Template类,其语法简化,适合最终用户编辑。这允许用户自定义他们的应用而无需更改应用

>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'

使用二进制数据记录

struct模块提供了pack()和unpack()函数,用于处理可变长度二进制记录格式。以下示例显示如何在不使用zipfile模块的情况下循环ZIP文件中的标头信息。 包代码“H”和“I”分别代表两个和四个字节的无符号数。 “<”表示它们是标准大小和小端字节顺序:

import struct

with open('myfile.zip', 'rb') as f:
    data = f.read()

start = 0
for i in range(3):                      # show the first 3 file headers
    start += 14
    fields = struct.unpack('

多线程

线程化是一种解耦非顺序依赖的任务的技术。 线程可用于提高接受用户输入的应用程序的响应能力,而其他任务在后台运行。 相关用例是与另一个线程中的计算并行运行I / O.

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.')

多线程应用程序的主要挑战是协调共享数据或其他资源的线程。 为此,线程模块提供了许多同步原语,包括锁,事件,条件变量和信号量。

日志

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')

使用列表工具

>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1

除了替代列表实现之外,该库还提供了其他工具,例如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')]

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]

十进制浮点算法

十进制模块为十进制浮点算法提供十进制数据类型。与二进制浮点的内置浮点实现相比,该类特别有用

>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73

你可能感兴趣的:(AI,Python)