<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](venv.xhtml "12. 虛擬環境和包") | - [上一頁](stdlib.xhtml "10. 標準庫簡介") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 教程](index.xhtml) ? - $('.inline-search').show(0); | # 11. 標準庫簡介 —— 第二部分 第二部分涵蓋了專業編程所需要的更高級的模塊。這些模塊很少用在小腳本中。 ## 11.1. 格式化輸出 [`reprlib`](../library/reprlib.xhtml#module-reprlib "reprlib: Alternate repr() implementation with size limits.") 模塊提供了一個定制化版本的 [`repr()`](../library/functions.xhtml#repr "repr") 函數,用于縮略顯示大型或深層嵌套的容器對象: ``` >>> import reprlib >>> reprlib.repr(set('supercalifragilisticexpialidocious')) "{'a', 'c', 'd', 'e', 'f', 'g', ...}" ``` [`pprint`](../library/pprint.xhtml#module-pprint "pprint: Data pretty printer.") 模塊提供了更加復雜的打印控制,其輸出的內置對象和用戶自定義對象能夠被解釋器直接讀取。當輸出結果過長而需要折行時,“美化輸出機制”會添加換行符和縮進,以更清楚地展示數據結構: ``` >>> import pprint >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', ... 'yellow'], 'blue']]] ... >>> pprint.pprint(t, width=30) [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]] ``` [`textwrap`](../library/textwrap.xhtml#module-textwrap "textwrap: Text wrapping and filling") 模塊能夠格式化文本段落,以適應給定的屏幕寬度: ``` >>> 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. ``` [`locale`](../library/locale.xhtml#module-locale "locale: Internationalization services.") 模塊處理與特定地域文化相關的數據格式。locale 模塊的 format 函數包含一個 grouping 屬性,可直接將數字格式化為帶有組分隔符的樣式: ``` >>> import locale >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') 'English_United States.1252' >>> conv = locale.localeconv() # get a mapping of conventions >>> x = 1234567.8 >>> locale.format("%d", x, grouping=True) '1,234,567' >>> locale.format_string("%s%.*f", (conv['currency_symbol'], ... conv['frac_digits'], x), grouping=True) '$1,234,567.80' ``` ## 11.2. 模板 [`string`](../library/string.xhtml#module-string "string: Common string operations.") 模塊包含一個通用的 [`Template`](../library/string.xhtml#string.Template "string.Template") 類,具有適用于最終用戶的簡化語法。它允許用戶在不更改應用邏輯的情況下定制自己的應用。 上述格式化操作是通過占位符實現的,占位符由 `$` 加上合法的 Python 標識符(只能包含字母、數字和下劃線)構成。一旦使用花括號將占位符括起來,就可以在后面直接跟上更多的字母和數字而無需空格分割。`$$` 將被轉義成單個字符 `$`: ``` >>> 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.' ``` 如果在字典或關鍵字參數中未提供某個占位符的值,那么 [`substitute()`](../library/string.xhtml#string.Template.substitute "string.Template.substitute") 方法將拋出 [`KeyError`](../library/exceptions.xhtml#KeyError "KeyError")。對于郵件合并類型的應用,用戶提供的數據有可能是不完整的,此時使用 [`safe_substitute()`](../library/string.xhtml#string.Template.safe_substitute "string.Template.safe_substitute") 方法更加合適 —— 如果數據缺失,它會直接將占位符原樣保留。 ``` >>> t = Template('Return the $item to $owner.') >>> d = dict(item='unladen swallow') >>> t.substitute(d) Traceback (most recent call last): ... KeyError: 'owner' >>> t.safe_substitute(d) 'Return the unladen swallow to $owner.' ``` Template 的子類可以自定義定界符。例如,以下是某個照片瀏覽器的批量重命名功能,采用了百分號作為日期、照片序號和照片格式的占位符: ``` >>> import time, os.path >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] >>> class BatchRename(Template): ... delimiter = '%' >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f >>> t = BatchRename(fmt) >>> date = time.strftime('%d%b%y') >>> for i, filename in enumerate(photofiles): ... base, ext = os.path.splitext(filename) ... newname = t.substitute(d=date, n=i, f=ext) ... print('{0} --> {1}'.format(filename, newname)) img_1074.jpg --> Ashley_0.jpg img_1076.jpg --> Ashley_1.jpg img_1077.jpg --> Ashley_2.jpg ``` 模板的另一個應用是將程序邏輯與多樣的格式化輸出細節分離開來。這使得對 XML 文件、純文本報表和 HTML 網絡報表使用自定義模板成為可能。 ## 11.3. 使用二進制數據記錄格式 [`struct`](../library/struct.xhtml#module-struct "struct: Interpret bytes as packed binary data.") 模塊提供了 [`pack()`](../library/struct.xhtml#struct.pack "struct.pack") 和 [`unpack()`](../library/struct.xhtml#struct.unpack "struct.unpack") 函數,用于處理不定長度的二進制記錄格式。下面的例子展示了在不使用 [`zipfile`](../library/zipfile.xhtml#module-zipfile "zipfile: Read and write ZIP-format archive files.") 模塊的情況下,如何循環遍歷一個 ZIP 文件的所有頭信息。Pack 代碼 `"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('<IIIHH', data[start:start+16]) crc32, comp_size, uncomp_size, filenamesize, extra_size = fields start += 16 filename = data[start:start+filenamesize] start += filenamesize extra = data[start:start+extra_size] print(filename, hex(crc32), comp_size, uncomp_size) start += extra_size + comp_size # skip to the next header ``` ## 11.4. 多線程 線程是一種對于非順序依賴的多個任務進行解耦的技術。多線程可以提高應用的響應效率,當接收用戶輸入的同時,保持其他任務在后臺運行。一個有關的應用場景是,將 I/O 和計算運行在兩個并行的線程中。 以下代碼展示了高階的 [`threading`](../library/threading.xhtml#module-threading "threading: Thread-based parallelism.") 模塊如何在后臺運行任務,且不影響主程序的繼續運行: ``` 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.') ``` 多線程應用面臨的主要挑戰是,相互協調的多個線程之間需要共享數據或其他資源。為此,threading 模塊提供了多個同步操作原語,包括線程鎖、事件、條件變量和信號量。 盡管這些工具非常強大,但微小的設計錯誤卻可以導致一些難以復現的問題。因此,實現多任務協作的首選方法是將對資源的所有請求集中到一個線程中,然后使用 [`queue`](../library/queue.xhtml#module-queue "queue: A synchronized queue class.") 模塊向該線程供應來自其他線程的請求。應用程序使用 [`Queue`](../library/queue.xhtml#queue.Queue "queue.Queue") 對象進行線程間通信和協調,更易于設計,更易讀,更可靠。 ## 11.5. 日志 [`logging`](../library/logging.xhtml#module-logging "logging: Flexible event logging system for applications.") 模塊提供功能齊全且靈活的日志記錄系統。在最簡單的情況下,日志消息被發送到文件或 `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') ``` 這會產生以下輸出: ``` WARNING:root:Warning:config file server.conf not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down ``` 默認情況下,informational 和 debugging 消息被壓制,輸出會發送到標準錯誤流。其他輸出選項包括將消息轉發到電子郵件,數據報,套接字或 HTTP 服務器。新的過濾器可以根據消息優先級選擇不同的路由方式:`DEBUG`,`INFO`,`WARNING`,`ERROR`,和 `CRITICAL`。 日志系統可以直接從 Python 配置,也可以從用戶配置文件加載,以便自定義日志記錄而無需更改應用程序。 ## 11.6. 弱引用 Python 會自動進行內存管理(對大多數對象進行引用計數并使用 [garbage collection](../glossary.xhtml#term-garbage-collection) 來清除循環引用)。 當某個對象的最后一個引用被移除后不久就會釋放其所占用的內存。 此方式對大多數應用來說都適用,但偶爾也必須在對象持續被其他對象所使用時跟蹤它們。 不幸的是,跟蹤它們將創建一個會令其永久化的引用。 [`weakref`](../library/weakref.xhtml#module-weakref "weakref: Support for weak references and weak dictionaries.") 模塊提供的工具可以不必創建引用就能跟蹤對象。 當對象不再需要時,它將自動從一個弱引用表中被移除,并為弱引用對象觸發一個回調。 典型應用包括對創建開銷較大的對象進行緩存: ``` >>> import weakref, gc >>> class A: ... def __init__(self, value): ... self.value = value ... def __repr__(self): ... return str(self.value) ... >>> a = A(10) # create a reference >>> d = weakref.WeakValueDictionary() >>> d['primary'] = a # does not create a reference >>> d['primary'] # fetch the object if it is still alive 10 >>> del a # remove the one reference >>> gc.collect() # run garbage collection right away 0 >>> d['primary'] # entry was automatically removed Traceback (most recent call last): File "<stdin>", line 1, in <module> d['primary'] # entry was automatically removed File "C:/python37/lib/weakref.py", line 46, in __getitem__ o = self.data[key]() KeyError: 'primary' ``` ## 11.7. 用于操作列表的工具 許多對于數據結構的需求可以通過內置列表類型來滿足。 但是,有時也會需要具有不同效費比的替代實現。 [`array`](../library/array.xhtml#module-array "array: Space efficient arrays of uniformly typed numeric values.") 模塊提供了一種 [`array()`](../library/array.xhtml#array.array "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]) ``` [`collections`](../library/collections.xhtml#module-collections "collections: Container datatypes") 模塊提供了一種 [`deque()`](../library/collections.xhtml#collections.deque "collections.deque") 對象,它類似于列表,但從左端添加和彈出的速度較快,而在中間查找的速度較慢。 此種對象適用于實現隊列和廣度優先樹搜索: ``` >>> 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) ``` 在替代的列表實現以外,標準庫也提供了其他工具,例如 [`bisect`](../library/bisect.xhtml#module-bisect "bisect: Array bisection algorithms for binary searching.") 模塊具有用于操作排序列表的函數: ``` >>> 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`](../library/heapq.xhtml#module-heapq "heapq: Heap queue algorithm (a.k.a. priority queue).") 模塊提供了基于常規列表來實現堆的函數。 最小值的條目總是保持在位置零。 這對于需要重復訪問最小元素而不希望運行完整列表排序的應用來說非常有用: ``` >>> 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`](../library/decimal.xhtml#module-decimal "decimal: Implementation of the General Decimal Arithmetic Specification.") 模塊提供了一種 [`Decimal`](../library/decimal.xhtml#decimal.Decimal "decimal.Decimal") 數據類型用于十進制浮點運算。 相比內置的 [`float`](../library/functions.xhtml#float "float") 二進制浮點實現,該類特別適用于 - 財務應用和其他需要精確十進制表示的用途, - 控制精度, - 控制四舍五入以滿足法律或監管要求, - 跟蹤有效小數位,或 - 用戶期望結果與手工完成的計算相匹配的應用程序。 例如,使用十進制浮點和二進制浮點數計算70美分手機和5%稅的總費用,會產生的不同結果。如果結果四舍五入到最接近的分數差異會更大: ``` >>> from decimal import * >>> round(Decimal('0.70') * Decimal('1.05'), 2) Decimal('0.74') >>> round(.70 * 1.05, 2) 0.73 ``` [`Decimal`](../library/decimal.xhtml#decimal.Decimal "decimal.Decimal") 表示的結果會保留尾部的零,并根據具有兩個有效位的被乘數自動推出四個有效位。 Decimal 可以模擬手工運算來避免當二進制浮點數無法精確表示十進制數時會導致的問題。 精確表示特性使得 [`Decimal`](../library/decimal.xhtml#decimal.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 ``` [`decimal`](../library/decimal.xhtml#module-decimal "decimal: Implementation of the General Decimal Arithmetic Specification.") 模塊提供了運算所需要的足夠精度: ``` >>> getcontext().prec = 36 >>> Decimal(1) / Decimal(7) Decimal('0.142857142857142857142857142857142857') ``` ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](venv.xhtml "12. 虛擬環境和包") | - [上一頁](stdlib.xhtml "10. 標準庫簡介") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 教程](index.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看