程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Introduction to Python zero foundation-11 introduction to the standard library - Part II

編輯:Python

11.  Introduction to standard library —— The second part

11.1.  Format output

reprlib  Module provides a customized version of  repr()  function , Used to abbreviate large or deeply nested container objects

pprint  The module provides more complex print control , The output built-in objects and user-defined objects can be read directly by the interpreter . When the output result is too long and needs to be folded ,“ Beautifying output mechanism ” Line breaks and indents will be added , To show the data structure more clearly .

textwrap  Module can format text paragraphs , To fit the given screen width .

locale  The module deals with data formats related to specific regional cultures .locale Modular format The function contains a grouping attribute , You can format numbers directly into a style with group separators .

11.2.  Templates

string  The module contains a generic  Template  class , Has simplified syntax for end users . It allows users to customize their own applications without changing the application logic .

11.3.  Use binary data record format

11.4.  Multithreading

Thread is a technique to decouple multiple tasks that are not sequence dependent . Multithreading can improve the response efficiency of applications , When receiving user input , Keep other tasks running in the background . A related application scenario is , take I/O And computing runs in two parallel threads .

The following code shows a high-order  threading  How the module runs tasks in the background , And does not affect the continued operation of the main program :

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

11.5.  logging

logging  The module provides a complete and flexible log recording system . In the simplest case , Log messages are sent to files or  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')

This produces the following output :

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

By default ,informational and debugging The news was suppressed , The output is sent to the standard error stream . Other output options include forwarding messages to e-mail , The datagram , Socket or HTTP The server . The new filter can select different routing methods according to message priority :DEBUG,INFO,WARNING,ERROR, and  CRITICAL.

The logging system can be directly from Python To configure , You can also load... From a user profile , To customize logging without changing the application .

11.6.  Weak reference

weakref  modular

11.7.  Tools for manipulating lists

array  The module provides a  array()  object , It's like a list , But only data of the same type can be stored and the storage density is higher . The following example demonstrates an array of unsigned binary values with two bytes as the storage unit ( The type code is  "H"), For ordinary lists , Each entry is stored as a standard Python Of int Objects usually occupy 16 Bytes :

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

collections The module provides a deque() object , It's like a list , But adding and ejecting from the left is faster , The speed of searching in the middle is slow . This kind of object is suitable for queue and breadth first tree search :

>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
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)

Outside the alternative list implementation , The standard library also provides other tools , for example  bisect  The module has functions for operating a sequence table :

>>> 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  Module provides functions to implement the heap based on the regular list . The entry of the minimum value is always kept at position zero . This is useful for applications that need to repeatedly access the smallest elements without running a full list sort :

>>> 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]

11.8.  Decimal floating point operations

decimal  The module provides a  Decimal  The data type is used for decimal floating-point operations . Compared with the built-in  float  Binary floating point implementation , This class is especially suitable for

  • Financial applications and other uses that require precise decimal representation ,

  • Control accuracy ,

  • Control rounding to meet legal or regulatory requirements ,

  • Tracking significant decimal places ,

  • The user expects the results to match the calculations done manually by the application .

for example , Yes 70 Calculation of telephone bill in cents 5% tax , Use decimal floating-point and binary floating-point numbers to calculate , Will produce different results . If the result is rounded to the nearest score, the difference will be obvious :

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

Decimal  The result of the representation will keep the zero of the tail , And automatically deduces four significant bits according to the multiplicator with two significant bits . Decimal You can simulate manual operations to avoid problems when binary floating-point numbers cannot accurately represent decimal numbers .

The precise representation of features makes  Decimal  Class can perform modulo operations and equality detection that are not applicable to binary floating-point numbers :

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

decimal  The module provides enough precision for the operation :

>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved