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

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                ### 11. 標準庫概覽 — 第II部分 第二部分提供了更高級的模塊用來支持專業編程的需要。這些模塊很少出現在小型的腳本里。 ### 11.1. 輸出格式 [reprlib](# "reprlib: Alternate repr() implementation with size limits.")模塊提供一個定制版的[repr()](# "repr")用于顯示大型或者深層嵌套容器: ~~~ >>> import reprlib >>> reprlib.repr(set('supercalifragilisticexpialidocious')) "set(['a', 'c', 'd', 'e', 'f', 'g', ...])" ~~~ [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](# "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](# "locale: Internationalization services.")模塊會訪問區域性特定數據格式的數據庫。分組屬性的區域設置的格式函數的格式設置的數字以直接的方式提供了組分隔符: ~~~ >>> 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](# "string: Common string operations.")模塊包括一個通用[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()](# "string.Template.substitute")方法將引發[KeyError](# "KeyError")。對于郵件-合并風格的應用程序,用戶提供的數據可能不完整,這時[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. 二進制數據記錄格式 The struct module provides pack() and unpack() functions for working with variable length binary record formats. The following example shows how to loop through header information in a ZIP file without using the zipfile module. Pack codes "H" and "I" represent two and four byte unsigned numbers respectively. The "<" indicates that they are standard size and in little-endian byte order: ~~~ 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](# "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.') ~~~ 多線程應用程序的最主要挑戰是協調線程間共享的數據或其他資源。為此目的,該線程模塊提供了許多同步原語包括鎖、 事件、 條件變量和信號量。 盡管這些工具很強大,很小的設計錯誤也可能導致很難復現的問題。因此,任務協調的首選方法是把對一個資源的所有訪問集中在一個單獨的線程中,然后使用[queue](# "queue: A synchronized queue class.")模塊用那個線程服務其他線程的請求。應用程序使用[Queue](# "queue.Queue")對象進行線程間的通信和協調將更容易設計、 更具可讀性和更可靠。 ### 11.5. 日志 [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 ~~~ 默認情況下,信息和調試消息被壓制并輸出到標準錯誤。其他輸出選項包括將消息通過email、 datagrams、sockets發送,或者發送到 HTTP 服務器。根據消息的優先級,新的過濾器可以選擇不同的方式:DEBUG、INFO、WARNING、ERROR和CRITICAL。 日志系統可以直接在 Python 代碼中定制,也可以不經過應用程序直接在一個用戶可編輯的配置文件中加載。 ### 11.6. 弱引用 Python 會自動進行內存管理 (對大多數的對象進行引用計數和[*垃圾回收*](#)以循環利用)。在最后一個引用消失后,內存會立即釋放。 這個方式對大多數應用程序工作良好,但是有時候會需要跟蹤對象,只要它們還被其它地方所使用。不幸的是,只是跟蹤它們也會創建一個引用,這將使它們永久保留。[weakref](# "weakref: Support for weak references and weak dictionaries.")模塊提供工具用來無需創建一個引用跟蹤對象。當不再需要該對象時,它會自動從 weakref 表中刪除并且會為 weakref 對象觸發一個回調。典型的應用包括緩存創建的時候需要很大開銷的對象: ~~~ >>> 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:/python34/lib/weakref.py", line 46, in __getitem__ o = self.data[key]() KeyError: 'primary' ~~~ ### 11.7. 列表工具 很多數據結構使用內置列表類型就可以滿足需求。然而,有時需要其它具有不同性能的替代實現。 The array module provides an array() object that is like a list that stores only homogeneous data and stores it more compactly. The following example shows an array of numbers stored as two byte unsigned binary numbers (typecode "H") rather than the usual 16 bytes per entry for regular lists of Python int objects: ~~~ >>> from array import array >>> a = array('H', [4000, 10, 700, 22222]) >>> sum(a) 26932 >>> a[1:3] array('H', [10, 700]) ~~~ [collections](# "collections: High-performance datatypes")模塊提供了一個[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](# "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](# "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](# "decimal: Implementation of the General Decimal Arithmetic Specification.")模塊提供一個[Decimal](# "decimal.Decimal")數據類型用于為十進制浮點運算。相比二進制浮點數內置的[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](# "decimal.Decimal")的結果總是保有結尾的0,自動從兩位精度延伸到4位。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](# "decimal: Implementation of the General Decimal Arithmetic Specification.")模塊提供任意精度的運算: ~~~ >>> getcontext().prec = 36 >>> Decimal(1) / Decimal(7) Decimal('0.142857142857142857142857142857142857') ~~~
                  <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>

                              哎呀哎呀视频在线观看