<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之旅 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](collections.abc.xhtml "collections.abc --- 容器的抽象基類") | - [上一頁](calendar.xhtml "calendar --- General calendar-related functions") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [數據類型](datatypes.xhtml) ? - $('.inline-search').show(0); | # [`collections`](#module-collections "collections: Container datatypes") --- 容器數據類型 **Source code:** [Lib/collections/\_\_init\_\_.py](https://github.com/python/cpython/tree/3.7/Lib/collections/__init__.py) \[https://github.com/python/cpython/tree/3.7/Lib/collections/\_\_init\_\_.py\] - - - - - - 這個模塊實現了特定目標的容器,以提供Python標準內建容器 [`dict`](stdtypes.xhtml#dict "dict") , [`list`](stdtypes.xhtml#list "list") , [`set`](stdtypes.xhtml#set "set") , 和 [`tuple`](stdtypes.xhtml#tuple "tuple") 的替代選擇。 [`namedtuple()`](#collections.namedtuple "collections.namedtuple") 創建命名元組子類的工廠函數 [`deque`](#collections.deque "collections.deque") 類似列表(list)的容器,實現了在兩端快速添加(append)和彈出(pop) [`ChainMap`](#collections.ChainMap "collections.ChainMap") 類似字典(dict)的容器類,將多個映射集合到一個視圖里面 [`Counter`](#collections.Counter "collections.Counter") 字典的子類,提供了可哈希對象的計數功能 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 字典的子類,保存了他們被添加的順序 [`defaultdict`](#collections.defaultdict "collections.defaultdict") 字典的子類,提供了一個工廠函數,為字典查詢提供一個默認值 [`UserDict`](#collections.UserDict "collections.UserDict") 封裝了字典對象,簡化了字典子類化 [`UserList`](#collections.UserList "collections.UserList") 封裝了列表對象,簡化了列表子類化 [`UserString`](#collections.UserString "collections.UserString") 封裝了列表對象,簡化了字符串子類化 在 3.3 版更改: 將 [Collections Abstract Base Classes](collections.abc.xhtml#collections-abstract-base-classes) 移到了 [`collections.abc`](collections.abc.xhtml#module-collections.abc "collections.abc: Abstract base classes for containers") 模塊. 在Python 3.7 為了保持兼容性,他們依然在這個模塊可見。最終會被全部移除掉。 ## [`ChainMap`](#collections.ChainMap "collections.ChainMap") 對象 3\.3 新版功能. 一個 [`ChainMap`](#collections.ChainMap "collections.ChainMap") 類是為了將多個映射快速的鏈接到一起,這樣它們就可以作為一個單元處理。它通常比創建一個新字典和多次調用 [`update()`](stdtypes.xhtml#dict.update "dict.update") 要快很多。 這個類可以用于模擬嵌套作用域,并且在模版化的時候比較有用。 *class* `collections.``ChainMap`(*\*maps*)一個 [`ChainMap`](#collections.ChainMap "collections.ChainMap") 將多個字典或者其他映射組合在一起,創建一個單獨的可更新的視圖。 如果沒有 *maps* 被指定,就提供一個默認的空字典,這樣一個新鏈至少有一個映射。 底層映射被存儲在一個列表中。這個列表是公開的,可以通過 *maps* 屬性存取和更新。沒有其他的狀態。 搜索查詢底層映射,直到一個鍵被找到。不同的是,寫,更新和刪除只操作第一個映射。 一個 [`ChainMap`](#collections.ChainMap "collections.ChainMap") 通過引用合并底層映射。 所以,如果一個底層映射更新了,這些更改會反映到 [`ChainMap`](#collections.ChainMap "collections.ChainMap") 。 支持所有常用字典方法。另外還有一個 *maps* 屬性(attribute),一個創建子上下文的方法(method), 一個存取它們首個映射的屬性(property): `maps`一個可以更新的映射列表。這個列表是按照第一次搜索到最后一次搜索的順序組織的。它是僅有的存儲狀態,可以被修改。列表最少包含一個映射。 `new_child`(*m=None*)返回一個新的 [`ChainMap`](#collections.ChainMap "collections.ChainMap") 類,包含了一個新映射(map),后面跟隨當前實例的全部映射(map)。如果 `m` 被指定,它就成為不同新的實例,就是在所有映射前加上 m,如果沒有指定,就加上一個空字典,這樣的話一個 `d.new_child()` 調用等價于 `ChainMap({}, *d.maps)` 。這個方法用于創建子上下文,不改變任何父映射的值。 在 3.4 版更改: 添加了 `m` 可選參數。 `parents`屬性返回一個新的 [`ChainMap`](#collections.ChainMap "collections.ChainMap") 包含所有的當前實例的映射,除了第一個。這樣可以在搜索的時候跳過第一個映射。 使用的場景類似在 [nested scopes](../glossary.xhtml#term-nested-scope) 嵌套作用域中使用 [`nonlocal`](../reference/simple_stmts.xhtml#nonlocal) 關鍵詞。用例也可以類比內建函數 [`super()`](functions.xhtml#super "super") 。一個 `d.parents` 的引用等價于 `ChainMap(*d.maps[1:])` 。 注意,一個 [`ChainMap()`](#collections.ChainMap "collections.ChainMap") 的迭代順序是通過掃描最后的映射來確定的: ``` >>> baseline = {'music': 'bach', 'art': 'rembrandt'} >>> adjustments = {'art': 'van gogh', 'opera': 'carmen'} >>> list(ChainMap(adjustments, baseline)) ['music', 'art', 'opera'] ``` 這給出了與 [`dict.update()`](stdtypes.xhtml#dict.update "dict.update") 調用序列相同的順序,從最后一個映射開始: ``` >>> combined = baseline.copy() >>> combined.update(adjustments) >>> list(combined) ['music', 'art', 'opera'] ``` 參見 - [MultiContext class](https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py) \[https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi\_context.py\] 在 Enthought [CodeTools package](https://github.com/enthought/codetools) \[https://github.com/enthought/codetools\] 有支持寫映射的選項。 - Django 的 [Context class](https://github.com/django/django/blob/master/django/template/context.py) \[https://github.com/django/django/blob/master/django/template/context.py\] 模版是只讀映射。它的上下文的push和pop特性也類似于 [`new_child()`](#collections.ChainMap.new_child "collections.ChainMap.new_child") 方法 [`parents`](#collections.ChainMap.parents "collections.ChainMap.parents") 屬性。 - [Nested Contexts recipe](https://code.activestate.com/recipes/577434/) \[https://code.activestate.com/recipes/577434/\] 提供了是否對第一個映射或其他映射進行寫和其他修改的選項。 - 一個 [極簡的只讀版 Chainmap](https://code.activestate.com/recipes/305268/) \[https://code.activestate.com/recipes/305268/\]. ### [`ChainMap`](#collections.ChainMap "collections.ChainMap") 例子和方法 這一節提供了多個使用鏈映射的案例。 模擬Python內部lookup鏈的例子 ``` import builtins pylookup = ChainMap(locals(), globals(), vars(builtins)) ``` 讓用戶指定的命令行參數優先于環境變量,優先于默認值的例子 ``` import os, argparse defaults = {'color': 'red', 'user': 'guest'} parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = {k:v for k, v in vars(namespace).items() if v} combined = ChainMap(command_line_args, os.environ, defaults) print(combined['color']) print(combined['user']) ``` 用 [`ChainMap`](#collections.ChainMap "collections.ChainMap") 類模擬嵌套上下文的例子 ``` c = ChainMap() # Create root context d = c.new_child() # Create nested child context e = c.new_child() # Child of c, independent from d e.maps[0] # Current context dictionary -- like Python's locals() e.maps[-1] # Root context -- like Python's globals() e.parents # Enclosing context chain -- like Python's nonlocals d['x'] = 1 # Set value in current context d['x'] # Get first key in the chain of contexts del d['x'] # Delete from current context list(d) # All nested values k in d # Check all nested values len(d) # Number of nested values d.items() # All nested items dict(d) # Flatten into a regular dictionary ``` [`ChainMap`](#collections.ChainMap "collections.ChainMap") 類只更新鏈中的第一個映射,但lookup會搜索整個鏈。 然而,如果需要深度寫和刪除,也可以很容易的通過定義一個子類來實現它 ``` class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down >>> d # display result DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'}) ``` ## [`Counter`](#collections.Counter "collections.Counter") 對象 一個計數器工具提供快速和方便的計數。比如 ``` >>> # Tally occurrences of words in a list >>> cnt = Counter() >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1 >>> cnt Counter({'blue': 3, 'red': 2, 'green': 1}) >>> # Find the ten most common words in Hamlet >>> import re >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower()) >>> Counter(words).most_common(10) [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)] ``` *class* `collections.``Counter`(\[*iterable-or-mapping*\])一個 [`Counter`](#collections.Counter "collections.Counter") 是一個 [`dict`](stdtypes.xhtml#dict "dict") 的子類,用于計數可哈希對象。它是一個集合,元素像字典鍵(key)一樣存儲,它們的計數存儲為值。計數可以是任何整數值,包括0和負數。 [`Counter`](#collections.Counter "collections.Counter") 類有點像其他語言中的 bags或multisets。 元素從一個 *iterable* 被計數或從其他的 *mapping* (or counter)初始化: ``` >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping >>> c = Counter(cats=4, dogs=8) # a new counter from keyword args ``` Counter對象有一個字典接口,如果引用的鍵沒有任何記錄,就返回一個0,而不是彈出一個 [`KeyError`](exceptions.xhtml#KeyError "KeyError") : ``` >>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 0 ``` 設置一個計數為0不會從計數器中移去一個元素。使用 `del` 來刪除它: ``` >>> c['sausage'] = 0 # counter entry with a zero count >>> del c['sausage'] # del actually removes the entry ``` 3\.1 新版功能. 計數器對象除了字典方法以外,還提供了三個其他的方法: `elements`()返回一個迭代器,每個元素重復計數的個數。元素順序是任意的。如果一個元素的計數小于1, [`elements()`](#collections.Counter.elements "collections.Counter.elements") 就會忽略它。 ``` >>> c = Counter(a=4, b=2, c=0, d=-2) >>> sorted(c.elements()) ['a', 'a', 'a', 'a', 'b', 'b'] ``` `most_common`(\[*n*\])返回一個列表,提供 *n* 個頻率最高的元素和計數。 如果沒提供 *n* ,或者是 `None` , [`most_common()`](#collections.Counter.most_common "collections.Counter.most_common") 返回計數器中的 *所有* 元素。相等個數的元素順序隨機: ``` >>> Counter('abracadabra').most_common(3) # doctest: +SKIP [('a', 5), ('r', 2), ('b', 2)] ``` `subtract`(\[*iterable-or-mapping*\])從 *迭代對象* 或 *映射對象* 減去元素。像 [`dict.update()`](stdtypes.xhtml#dict.update "dict.update") 但是是減去,而不是替換。輸入和輸出都可以是0或者負數。 ``` >>> c = Counter(a=4, b=2, c=0, d=-2) >>> d = Counter(a=1, b=2, c=3, d=4) >>> c.subtract(d) >>> c Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6}) ``` 3\.2 新版功能. 通常字典方法都可用于 [`Counter`](#collections.Counter "collections.Counter") 對象,除了有兩個方法工作方式與字典并不相同。 `fromkeys`(*iterable*)這個類方法沒有在 [`Counter`](#collections.Counter "collections.Counter") 中實現。 `update`(\[*iterable-or-mapping*\])從 *迭代對象* 計數元素或者 從另一個 *映射對象* (或計數器) 添加。 像 [`dict.update()`](stdtypes.xhtml#dict.update "dict.update") 但是是加上,而不是替換。另外,*迭代對象* 應該是序列元素,而不是一個 `(key, value)` 對。 [`Counter`](#collections.Counter "collections.Counter") 對象的常用案例 ``` sum(c.values()) # total of all counts c.clear() # reset all counts list(c) # list unique elements set(c) # convert to a set dict(c) # convert to a regular dictionary c.items() # convert to a list of (elem, cnt) pairs Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs c.most_common()[:-n-1:-1] # n least common elements +c # remove zero and negative counts ``` 提供了幾個數學操作,可以結合 [`Counter`](#collections.Counter "collections.Counter") 對象,以生產 multisets (計數器中大于0的元素)。 加和減,結合計數器,通過加上或者減去元素的相應計數。交集和并集返回相應計數的最小或最大值。每種操作都可以接受帶符號的計數,但是輸出會忽略掉結果為零或者小于零的計數。 ``` >>> c = Counter(a=3, b=1) >>> d = Counter(a=1, b=2) >>> c + d # add two counters together: c[x] + d[x] Counter({'a': 4, 'b': 3}) >>> c - d # subtract (keeping only positive counts) Counter({'a': 2}) >>> c & d # intersection: min(c[x], d[x]) # doctest: +SKIP Counter({'a': 1, 'b': 1}) >>> c | d # union: max(c[x], d[x]) Counter({'a': 3, 'b': 2}) ``` 單目加和減(一元操作符)意思是從空計數器加或者減去。 ``` >>> c = Counter(a=2, b=-4) >>> +c Counter({'a': 2}) >>> -c Counter({'b': 4}) ``` 3\.3 新版功能: 添加了對一元加,一元減和位置集合操作的支持。 注解 計數器主要是為了表達運行的正的計數而設計;但是,小心不要預先排除負數或者其他類型。為了幫助這些用例,這一節記錄了最小范圍和類型限制。 - [`Counter`](#collections.Counter "collections.Counter") 類是一個字典的子類,不限制鍵和值。值用于表示計數,但你實際上 *可以* 存儲任何其他值。 - [`most_common()`](#collections.Counter.most_common "collections.Counter.most_common") 方法在值需要排序的時候用。 - 原地操作比如 `c[key] += 1` , 值類型只需要支持加和減。 所以分數,小數,和十進制都可以用,負值也可以支持。這兩個方法 [`update()`](#collections.Counter.update "collections.Counter.update") 和 [`subtract()`](#collections.Counter.subtract "collections.Counter.subtract") 的輸入和輸出也一樣支持負數和0。 - Multiset多集合方法只為正值的使用情況設計。輸入可以是負數或者0,但只輸出計數為正的值。沒有類型限制,但值類型需要支持加,減和比較操作。 - [`elements()`](#collections.Counter.elements "collections.Counter.elements") 方法要求正整數計數。忽略0和負數計數。 參見 - [Bag class](https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html) \[https://www.gnu.org/software/smalltalk/manual-base/html\_node/Bag.html\] 在 Smalltalk。 - Wikipedia 鏈接 [Multisets](https://en.wikipedia.org/wiki/Multiset) \[https://en.wikipedia.org/wiki/Multiset\]. - [C++ multisets](http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm) \[http://www.java2s.com/Tutorial/Cpp/0380\_\_set-multiset/Catalog0380\_\_set-multiset.htm\] 教程和例子。 - 數學操作和多集合用例,參考 *Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19* 。 - 在給定數量和集合元素枚舉所有不同的多集合,參考 [`itertools.combinations_with_replacement()`](itertools.xhtml#itertools.combinations_with_replacement "itertools.combinations_with_replacement") ``` map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC ``` ## [`deque`](#collections.deque "collections.deque") 對象 *class* `collections.``deque`(\[*iterable*\[, *maxlen*\]\])返回一個新的雙向隊列對象,從左到右初始化(用方法 [`append()`](#collections.deque.append "collections.deque.append")) ,從 *iterable* (迭代對象) 數據創建。如果 *iterable* 沒有指定,新隊列為空。 Deque隊列是由棧或者queue隊列生成的(發音是 “deck”,”double-ended queue”的簡稱)。Deque 支持線程安全,內存高效添加(append)和彈出(pop),從兩端都可以,兩個方向的大概開銷都是 O(1) 復雜度。 雖然 [`list`](stdtypes.xhtml#list "list") 對象也支持類似操作,不過這里優化了定長操作和 `pop(0)` 和 `insert(0, v)` 的開銷。它們引起 O(n) 內存移動的操作,改變底層數據表達的大小和位置。 如果 *maxlen* 沒有指定或者是 `None` ,deques 可以增長到任意長度。否則,deque就限定到指定最大長度。一旦限定長度的deque滿了,當新項加入時,同樣數量的項就從另一端彈出。限定長度deque提供類似Unix filter `tail` 的功能。它們同樣可以用與追蹤最近的交換和其他數據池活動。 雙向隊列(deque)對象支持以下方法: `append`(*x*)添加 *x* 到右端。 `appendleft`(*x*)添加 *x* 到左端。 `clear`()移除所有元素,使其長度為0. `copy`()創建一份淺拷貝。 3\.5 新版功能. `count`(*x*)計算deque中個數等于 *x* 的元素。 3\.2 新版功能. `extend`(*iterable*)擴展deque的右側,通過添加iterable參數中的元素。 `extendleft`(*iterable*)擴展deque的左側,通過添加iterable參數中的元素。注意,左添加時,在結果中iterable參數中的順序將被反過來添加。 `index`(*x*\[, *start*\[, *stop*\]\])返回第 *x* 個元素(從 *start* 開始計算,在 *stop* 之前)。返回第一個匹配,如果沒找到的話,升起 [`ValueError`](exceptions.xhtml#ValueError "ValueError") 。 3\.5 新版功能. `insert`(*i*, *x*)在位置 *i* 插入 *x* 。 如果插入會導致一個限長deque超出長度 *maxlen* 的話,就升起一個 [`IndexError`](exceptions.xhtml#IndexError "IndexError") 。 3\.5 新版功能. `pop`()移去并且返回一個元素,deque最右側的那一個。如果沒有元素的話,就升起 [`IndexError`](exceptions.xhtml#IndexError "IndexError") 索引錯誤。 `popleft`()移去并且返回一個元素,deque最左側的那一個。如果沒有元素的話,就升起 [`IndexError`](exceptions.xhtml#IndexError "IndexError") 索引錯誤。 `remove`(*value*)移去找到的第一個 *value*。 如果沒有的話就升起 [`ValueError`](exceptions.xhtml#ValueError "ValueError") 。 `reverse`()將deque逆序排列。返回 `None` 。 3\.2 新版功能. `rotate`(*n=1*)向右循環移動 *n* 步。 如果 *n* 是負數,就向左循環。 如果deque不是空的,向右循環移動一步就等價于 `d.appendleft(d.pop())` , 向左循環一步就等價于 `d.append(d.popleft())` 。 Deque對象同樣提供了一個只讀屬性: `maxlen`Deque的最大尺寸,如果沒有限定的話就是 `None` 。 3\.1 新版功能. 除了以上,deque還支持迭代,清洗,`len(d)`, `reversed(d)`, `copy.copy(d)`, `copy.deepcopy(d)`, 成員測試 [`in`](../reference/expressions.xhtml#in) 操作符,和下標引用 `d[-1]` 。索引存取在兩端的復雜度是 O(1), 在中間的復雜度比 O(n) 略低。要快速存取,使用list來替代。 Deque從版本3.5開始支持 `__add__()`, `__mul__()`, 和 `__imul__()` 。 示例: ``` >>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements ... print(elem.upper()) G H I >>> d.append('j') # add a new entry to the right side >>> d.appendleft('f') # add a new entry to the left side >>> d # show the representation of the deque deque(['f', 'g', 'h', 'i', 'j']) >>> d.pop() # return and remove the rightmost item 'j' >>> d.popleft() # return and remove the leftmost item 'f' >>> list(d) # list the contents of the deque ['g', 'h', 'i'] >>> d[0] # peek at leftmost item 'g' >>> d[-1] # peek at rightmost item 'i' >>> list(reversed(d)) # list the contents of a deque in reverse ['i', 'h', 'g'] >>> 'h' in d # search the deque True >>> d.extend('jkl') # add multiple elements at once >>> d deque(['g', 'h', 'i', 'j', 'k', 'l']) >>> d.rotate(1) # right rotation >>> d deque(['l', 'g', 'h', 'i', 'j', 'k']) >>> d.rotate(-1) # left rotation >>> d deque(['g', 'h', 'i', 'j', 'k', 'l']) >>> deque(reversed(d)) # make a new deque in reverse order deque(['l', 'k', 'j', 'i', 'h', 'g']) >>> d.clear() # empty the deque >>> d.pop() # cannot pop from an empty deque Traceback (most recent call last): File "<pyshell#6>", line 1, in -toplevel- d.pop() IndexError: pop from an empty deque >>> d.extendleft('abc') # extendleft() reverses the input order >>> d deque(['c', 'b', 'a']) ``` ### [`deque`](#collections.deque "collections.deque") 用法 這一節展示了deque的多種用法。 限長deque提供了類似Unix `tail` 過濾功能 ``` def tail(filename, n=10): 'Return the last n lines of a file' with open(filename) as f: return deque(f, n) ``` 另一個用法是維護一個近期添加元素的序列,通過從右邊添加和從左邊彈出 ``` def moving_average(iterable, n=3): # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0 # http://en.wikipedia.org/wiki/Moving_average it = iter(iterable) d = deque(itertools.islice(it, n-1)) d.appendleft(0) s = sum(d) for elem in it: s += elem - d.popleft() d.append(elem) yield s / n ``` 一個 [輪詢調度器](https://en.wikipedia.org/wiki/Round-robin_scheduling) \[https://en.wikipedia.org/wiki/Round-robin\_scheduling\] 可以通過在 [`deque`](#collections.deque "collections.deque") 中放入迭代器來實現。值從當前迭代器的位置0被取出并暫存(yield)。 如果這個迭代器消耗完畢,就用 [`popleft()`](#collections.deque.popleft "collections.deque.popleft") 將其從對列中移去;否則,就通過 [`rotate()`](#collections.deque.rotate "collections.deque.rotate") 將它移到隊列的末尾 ``` def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" iterators = deque(map(iter, iterables)) while iterators: try: while True: yield next(iterators[0]) iterators.rotate(-1) except StopIteration: # Remove an exhausted iterator. iterators.popleft() ``` [`rotate()`](#collections.deque.rotate "collections.deque.rotate") 方法提供了一種方式來實現 [`deque`](#collections.deque "collections.deque") 切片和刪除。 例如, 一個純的Python `del d[n]` 實現依賴于 `rotate()` 來定位要彈出的元素 ``` def delete_nth(d, n): d.rotate(-n) d.popleft() d.rotate(n) ``` 要實現 [`deque`](#collections.deque "collections.deque") 切片, 使用一個類似的方法,應用 [`rotate()`](#collections.deque.rotate "collections.deque.rotate") 將目標元素放到左邊。通過 [`popleft()`](#collections.deque.popleft "collections.deque.popleft") 移去老的條目(entries),通過 [`extend()`](#collections.deque.extend "collections.deque.extend") 添加新的條目, 然后反向 rotate。這個方法可以最小代價實現命令式的棧操作,諸如 `dup`, `drop`, `swap`, `over`, `pick`, `rot`, 和 `roll` 。 ## [`defaultdict`](#collections.defaultdict "collections.defaultdict") 對象 *class* `collections.``defaultdict`(\[*default\_factory*\[, *...*\]\])返回一個新的類似字典的對象。 [`defaultdict`](#collections.defaultdict "collections.defaultdict") 是內置 [`dict`](stdtypes.xhtml#dict "dict") 類的子類。它重載了一個方法并添加了一個可寫的實例變量。其余的功能與 [`dict`](stdtypes.xhtml#dict "dict") 類相同,此處不再重復說明。 第一個參數 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 提供了一個初始值。它默認為 `None` 。所有的其他參數都等同與 [`dict`](stdtypes.xhtml#dict "dict") 構建器中的參數對待,包括關鍵詞參數。 [`defaultdict`](#collections.defaultdict "collections.defaultdict") 對象除了支持 [`dict`](stdtypes.xhtml#dict "dict") 的操作,還支持下面的方法作為擴展: `__missing__`(*key*)如果 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 是 `None` , 它就升起一個 [`KeyError`](exceptions.xhtml#KeyError "KeyError") 并將 *key* 作為參數。 如果 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 不為 `None` , 它就會會被調用,不帶參數,為 *key* 提供一個默認值, 這個值和 *key* 作為一個對被插入到字典中,并返回。 如果調用 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 升起了一個例外,這個例外就被擴散傳遞,不經過改變。 這個方法在查詢鍵值失敗時,會被 [`dict`](stdtypes.xhtml#dict "dict") 中的 [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") 調用。不管它是返回值或升起例外,都會被 [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") 傳遞。 注意 [`__missing__()`](#collections.defaultdict.__missing__ "collections.defaultdict.__missing__") *不會* 被 [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") 以外的其他方法調用。意思就是 `get()` 會向正常的dict那樣返回 `None` ,而不是使用 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 。 [`defaultdict`](#collections.defaultdict "collections.defaultdict") 支持以下實例變量: `default_factory`這個屬性被 [`__missing__()`](#collections.defaultdict.__missing__ "collections.defaultdict.__missing__") 方法使用;它從構建器的第一個參數初始化,如果提供了的話,否則就是 `None` 。 ### [`defaultdict`](#collections.defaultdict "collections.defaultdict") 例子 使用 [`list`](stdtypes.xhtml#list "list") 作為 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") ,很容易將序列作為鍵值對加入字典: ``` >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) >>> for k, v in s: ... d[k].append(v) ... >>> sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] ``` 當每個鍵第一次遇見時,它還沒有在字典里面;所以條目自動創建,通過 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 方法,并返回一個空的 [`list`](stdtypes.xhtml#list "list") 。 `list.append()` 操作添加值到這個新的列表里。當鍵再次被存取時,就正常操作, `list.append()` 添加另一個值到列表中。這個計數比它的等價方法 [`dict.setdefault()`](stdtypes.xhtml#dict.setdefault "dict.setdefault") 要快速和簡單: ``` >>> d = {} >>> for k, v in s: ... d.setdefault(k, []).append(v) ... >>> sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] ``` 設置 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 為 [`int`](functions.xhtml#int "int") ,使 [`defaultdict`](#collections.defaultdict "collections.defaultdict") 在計數方面發揮好的作用(像其他語言中的bag或multiset): ``` >>> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> sorted(d.items()) [('i', 4), ('m', 1), ('p', 2), ('s', 4)] ``` 當一個字母首次遇到時,它就查詢失敗,所以 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 調用 [`int()`](functions.xhtml#int "int") 來提供一個整數0作為默認值。自增操作然后建立對每個字母的計數。 函數 [`int()`](functions.xhtml#int "int") 總是返回0,是常數函數的特殊情況。一個更快和靈活的方法是使用lambda函數,可以提供任何常量值(不只是0): ``` >>> def constant_factory(value): ... return lambda: value >>> d = defaultdict(constant_factory('<missing>')) >>> d.update(name='John', action='ran') >>> '%(name)s %(action)s to %(object)s' % d 'John ran to <missing>' ``` 設置 [`default_factory`](#collections.defaultdict.default_factory "collections.defaultdict.default_factory") 為 [`set`](stdtypes.xhtml#set "set") 使 [`defaultdict`](#collections.defaultdict "collections.defaultdict") 用于構建字典集合: ``` >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] >>> d = defaultdict(set) >>> for k, v in s: ... d[k].add(v) ... >>> sorted(d.items()) [('blue', {2, 4}), ('red', {1, 3})] ``` ## [`namedtuple()`](#collections.namedtuple "collections.namedtuple") 命名元組的工廠函數 命名元組賦予每個位置一個含義,提供可讀性和自文檔性。它們可以用于任何普通元組,并添加了通過名字獲取值的能力,通過索引值也是可以的。 `collections.``namedtuple`(*typename*, *field\_names*, *\**, *rename=False*, *defaults=None*, *module=None*)返回一個新的元組子類,名為 *typename* 。這個新的子類用于創建類元組的對象,可以通過域名來獲取屬性值,同樣也可以通過索引和迭代獲取值。子類實例同樣有文檔字符串(類名和域名)另外一個有用的 [`__repr__()`](../reference/datamodel.xhtml#object.__repr__ "object.__repr__") 方法,以 `name=value` 格式列明了元組內容。 *field\_names* 是一個像 `[‘x’, ‘y’]` 一樣的字符串序列。另外 *field\_names* 可以是一個純字符串,用空白或逗號分隔開元素名,比如 `'x y'` 或者 `'x, y'` 。 任何有效的Python 標識符都可以作為域名,除了下劃線開頭的那些。有效標識符由字母,數字,下劃線組成,但首字母不能是數字或下劃線,另外不能是關鍵詞 [`keyword`](keyword.xhtml#module-keyword "keyword: Test whether a string is a keyword in Python.") 比如 *class*, *for*, *return*, *global*, *pass*, 或 *raise* 。 如果 *rename* 為真, 無效域名會自動轉換成位置名。比如 `['abc', 'def', 'ghi', 'abc']` 轉換成 `['abc', '_1', 'ghi', '_3']` , 消除關鍵詞 `def` 和重復域名 `abc` 。 *defaults* 可以為 `None` 或者是一個默認值的 [iterable](../glossary.xhtml#term-iterable) 。如果一個默認值域必須跟其他沒有默認值的域在一起出現,*defaults* 就應用到最右邊的參數。比如如果域名 `['x', 'y', 'z']` 和默認值 `(1, 2)` ,那么 `x` 就必須指定一個參數值 ,`y` 默認值 `1` , `z` 默認值 `2` 。 如果 *module* 值有定義,命名元組的 `__module__` 屬性值就被設置。 命名元組實例沒有字典,所以它們要更輕量,并且占用更小內存。 在 3.1 版更改: 添加了對 *rename* 的支持。 在 3.6 版更改: *verbose* 和 *rename* 參數成為 [僅限關鍵字參數](../glossary.xhtml#keyword-only-parameter). 在 3.6 版更改: 添加了 *module* 參數。 在 3.7 版更改: 移去了 *verbose* 參數和屬性 `_source` 。 在 3.7 版更改: 添加了 *defaults* 參數和 `_field_defaults` 屬性。 ``` >>> # Basic example >>> Point = namedtuple('Point', ['x', 'y']) >>> p = Point(11, y=22) # instantiate with positional or keyword arguments >>> p[0] + p[1] # indexable like the plain tuple (11, 22) 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> p # readable __repr__ with a name=value style Point(x=11, y=22) ``` 命名元組尤其有用于賦值 [`csv`](csv.xhtml#module-csv "csv: Write and read tabular data to and from delimited files.") [`sqlite3`](sqlite3.xhtml#module-sqlite3 "sqlite3: A DB-API 2.0 implementation using SQLite 3.x.") 模塊返回的元組 ``` EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') import csv for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))): print(emp.name, emp.title) import sqlite3 conn = sqlite3.connect('/companydata') cursor = conn.cursor() cursor.execute('SELECT name, age, title, department, paygrade FROM employees') for emp in map(EmployeeRecord._make, cursor.fetchall()): print(emp.name, emp.title) ``` 除了繼承元組的方法,命名元組還支持三個額外的方法和兩個屬性。為了防止域名沖突,方法和屬性以下劃線開始。 *classmethod* `somenamedtuple.``_make`(*iterable*)類方法從存在的序列或迭代實例創建一個新實例。 ``` >>> t = [11, 22] >>> Point._make(t) Point(x=11, y=22) ``` `somenamedtuple.``_asdict`()返回一個新的 [`dict`](stdtypes.xhtml#dict "dict") ,它將字段名稱映射到它們對應的值: ``` >>> p = Point(x=11, y=22) >>> p._asdict() OrderedDict([('x', 11), ('y', 22)]) ``` 在 3.1 版更改: 返回一個 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 而不是 [`dict`](stdtypes.xhtml#dict "dict") 。 `somenamedtuple.``_replace`(*\*\*kwargs*)返回一個新的命名元組實例,并將指定域替換為新的值 ``` >>> p = Point(x=11, y=22) >>> p._replace(x=33) Point(x=33, y=22) >>> for partnum, record in inventory.items(): ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now()) ``` `somenamedtuple.``_fields`字符串元組列出了域名。用于提醒和從現有元組創建一個新的命名元組類型。 ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` `somenamedtuple.``_field_defaults`默認值的字典。 ``` >>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0]) >>> Account._field_defaults {'balance': 0} >>> Account('premium') Account(type='premium', balance=0) ``` 要獲取這個名字域的值,使用 [`getattr()`](functions.xhtml#getattr "getattr") 函數 : ``` >>> getattr(p, 'x') 11 ``` 要將字典轉換為命名元組,請使用 `**` 運算符(如 [解包參數列表](../tutorial/controlflow.xhtml#tut-unpacking-arguments) 中所述): ``` >>> d = {'x': 11, 'y': 22} >>> Point(**d) Point(x=11, y=22) ``` 因為一個命名元組是一個正常的Python類,它可以很容易的通過子類更改功能。這里是如何添加一個計算域和定寬輸出打印格式: ``` >>> class Point(namedtuple('Point', ['x', 'y'])): ... __slots__ = () ... @property ... def hypot(self): ... return (self.x ** 2 + self.y ** 2) ** 0.5 ... def __str__(self): ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) >>> for p in Point(3, 4), Point(14, 5/7): ... print(p) Point: x= 3.000 y= 4.000 hypot= 5.000 Point: x=14.000 y= 0.714 hypot=14.018 ``` 上面的子類設置 `__slots__` 為一個空元組。通過阻止創建實例字典保持了較低的內存開銷。 子類化對于添加和存儲新的名字域是無效的。應當通過 [`_fields`](#collections.somenamedtuple._fields "collections.somenamedtuple._fields") 創建一個新的命名元組來實現它: ``` >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) ``` 文檔字符串可以自定義,通過直接賦值給 `__doc__` 屬性: ``` >>> Book = namedtuple('Book', ['id', 'title', 'authors']) >>> Book.__doc__ += ': Hardcover book in active collection' >>> Book.id.__doc__ = '13-digit ISBN' >>> Book.title.__doc__ = 'Title of first printing' >>> Book.authors.__doc__ = 'List of authors sorted by last name' ``` 在 3.5 版更改: 文檔字符串屬性變成可寫。 默認值可以用 [`_replace()`](#collections.somenamedtuple._replace "collections.somenamedtuple._replace") 來實現, 通過自定義一個原型實例: ``` >>> Account = namedtuple('Account', 'owner balance transaction_count') >>> default_account = Account('<owner name>', 0.0, 0) >>> johns_account = default_account._replace(owner='John') >>> janes_account = default_account._replace(owner='Jane') ``` 參見 - 請參閱 [`typing.NamedTuple`](typing.xhtml#typing.NamedTuple "typing.NamedTuple") ,以獲取為命名元組添加類型提示的方法。 它還使用 [`class`](../reference/compound_stmts.xhtml#class) 關鍵字提供了一種優雅的符號: ``` class Component(NamedTuple): part_number: int weight: float description: Optional[str] = None ``` - 對于以字典為底層的可變域名, 參考 [`types.SimpleNamespace()`](types.xhtml#types.SimpleNamespace "types.SimpleNamespace") 。 - [`dataclasses`](dataclasses.xhtml#module-dataclasses "dataclasses: Generate special methods on user-defined classes.") 模塊提供了一個裝飾器和一些函數,用于自動將生成的特殊方法添加到用戶定義的類中。 ## [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 對象 有序詞典就像常規詞典一樣,但有一些與排序操作相關的額外功能。由于內置的 [`dict`](stdtypes.xhtml#dict "dict") 類獲得了記住插入順序的能力(在 Python 3.7 中保證了這種新行為),它們變得不那么重要了。 一些與 [`dict`](stdtypes.xhtml#dict "dict") 的不同仍然存在: - 常規的 [`dict`](stdtypes.xhtml#dict "dict") 被設計為非常擅長映射操作。 跟蹤插入順序是次要的。 - [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 旨在擅長重新排序操作。 空間效率、迭代速度和更新操作的性能是次要的。 - 算法上, [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 可以比 [`dict`](stdtypes.xhtml#dict "dict") 更好地處理頻繁的重新排序操作。 這使其適用于跟蹤最近的訪問(例如在 [LRU cache](https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237) \[https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237\] 中)。 - 對于 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") ,相等操作檢查匹配順序。 - [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 類的 `popitem()` 方法有不同的簽名。它接受一個可選參數來指定彈出哪個元素。 - [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 類有一個 `move_to_end()` 方法,可以有效地將元素移動到任一端。 - Python 3.8之前, [`dict`](stdtypes.xhtml#dict "dict") 缺少 [`__reversed__()`](../reference/datamodel.xhtml#object.__reversed__ "object.__reversed__") 方法。 *class* `collections.``OrderedDict`(\[*items*\])返回一個 [`dict`](stdtypes.xhtml#dict "dict") 子類的實例,它具有專門用于重新排列字典順序的方法。 3\.1 新版功能. `popitem`(*last=True*)有序字典的 [`popitem()`](#collections.OrderedDict.popitem "collections.OrderedDict.popitem") 方法移除并返回一個 (key, value) 鍵值對。 如果 *last* 值為真,則按 LIFO 后進先出的順序返回鍵值對,否則就按 FIFO 先進先出的順序返回鍵值對。 `move_to_end`(*key*, *last=True*)將現有 *key* 移動到有序字典的任一端。 如果 *last* 為真值(默認)則將元素移至末尾;如果 *last* 為假值則將元素移至開頭。如果 *key* 不存在則會觸發 [`KeyError`](exceptions.xhtml#KeyError "KeyError"): ``` >>> d = OrderedDict.fromkeys('abcde') >>> d.move_to_end('b') >>> ''.join(d.keys()) 'acdeb' >>> d.move_to_end('b', last=False) >>> ''.join(d.keys()) 'bacde' ``` 3\.2 新版功能. 相對于通常的映射方法,有序字典還另外提供了逆序迭代的支持,通過 [`reversed()`](functions.xhtml#reversed "reversed") 。 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 之間的相等測試是順序敏感的,實現為 `list(od1.items())==list(od2.items())` 。 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 對象和其他的 [`Mapping`](collections.abc.xhtml#collections.abc.Mapping "collections.abc.Mapping") 的相等測試,是順序敏感的字典測試。這允許 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 替換為任何字典可以使用的場所。 在 3.5 版更改: [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 的項(item),鍵(key)和值(value) [視圖](../glossary.xhtml#term-dictionary-view) 現在支持逆序迭代,通過 [`reversed()`](functions.xhtml#reversed "reversed") 。 在 3.6 版更改: [**PEP 468**](https://www.python.org/dev/peps/pep-0468) \[https://www.python.org/dev/peps/pep-0468\] 贊成將關鍵詞參數的順序保留, 通過傳遞給 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 構造器和它的 `update()` 方法。 ### [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 例子和用法 創建記住鍵值 *最后* 插入順序的有序字典變體很簡單。 如果新條目覆蓋現有條目,則原始插入位置將更改并移至末尾: ``` class LastUpdatedOrderedDict(OrderedDict): 'Store items in the order the keys were last added' def __setitem__(self, key, value): super().__setitem__(key, value) super().move_to_end(key) ``` 一個 [`OrderedDict`](#collections.OrderedDict "collections.OrderedDict") 對于實現 [`functools.lru_cache()`](functools.xhtml#functools.lru_cache "functools.lru_cache") 的變體也很有用: ``` class LRU(OrderedDict): 'Limit size, evicting the least recently looked-up key when full' def __init__(self, maxsize=128, *args, **kwds): self.maxsize = maxsize super().__init__(*args, **kwds) def __getitem__(self, key): value = super().__getitem__(key) self.move_to_end(key) return value def __setitem__(self, key, value): super().__setitem__(key, value) if len(self) > self.maxsize: oldest = next(iter(self)) del self[oldest] ``` ## [`UserDict`](#collections.UserDict "collections.UserDict") 對象 [`UserDict`](#collections.UserDict "collections.UserDict") 類是用作字典對象的外包裝。對這個類的需求已部分由直接創建 [`dict`](stdtypes.xhtml#dict "dict") 的子類的功能所替代;不過,這個類處理起來更容易,因為底層的字典可以作為屬性來訪問。 *class* `collections.``UserDict`(\[*initialdata*\])模擬一個字典類。這個實例的內容保存為一個正常字典, 可以通過 [`UserDict`](#collections.UserDict "collections.UserDict") 實例的 [`data`](#collections.UserDict.data "collections.UserDict.data") 屬性存取。如果提供了 *initialdata* 值, [`data`](#collections.UserDict.data "collections.UserDict.data") 就被初始化為它的內容;注意一個 *initialdata* 的引用不會被保留作為其他用途。 [`UserDict`](#collections.UserDict "collections.UserDict") 實例提供了以下屬性作為擴展方法和操作的支持: `data`一個真實的字典,用于保存 [`UserDict`](#collections.UserDict "collections.UserDict") 類的內容。 ## [`UserList`](#collections.UserList "collections.UserList") 對象 這個類封裝了列表對象。它是一個有用的基礎類,對于你想自定義的類似列表的類,可以繼承和覆蓋現有的方法,也可以添加新的方法。這樣我們可以對列表添加新的行為。 對這個類的需求已部分由直接創建 [`list`](stdtypes.xhtml#list "list") 的子類的功能所替代;不過,這個類處理起來更容易,因為底層的列表可以作為屬性來訪問。 *class* `collections.``UserList`(\[*list*\])模擬一個列表。這個實例的內容被保存為一個正常列表,通過 [`UserList`](#collections.UserList "collections.UserList") 的 [`data`](#collections.UserList.data "collections.UserList.data") 屬性存取。實例內容被初始化為一個 *list* 的copy,默認為 `[]` 空列表。 *list* 可以是迭代對象,比如一個Python列表,或者一個 [`UserList`](#collections.UserList "collections.UserList") 對象。 [`UserList`](#collections.UserList "collections.UserList") 提供了以下屬性作為可變序列的方法和操作的擴展: `data`一個 [`list`](stdtypes.xhtml#list "list") 對象用于存儲 [`UserList`](#collections.UserList "collections.UserList") 的內容。 **子類化的要求:** [`UserList`](#collections.UserList "collections.UserList") 的子類需要提供一個構造器,可以無參數調用,或者一個參數調用。返回一個新序列的列表操作需要創建一個實現類的實例。它假定了構造器可以以一個參數進行調用,這個參數是一個序列對象,作為數據源。 如果一個分離的類不希望依照這個需求,所有的特殊方法就必須重寫;請參照源代碼進行修改。 ## [`UserString`](#collections.UserString "collections.UserString") 對象 [`UserString`](#collections.UserString "collections.UserString") 類是用作字符串對象的外包裝。對這個類的需求已部分由直接創建 [`str`](stdtypes.xhtml#str "str") 的子類的功能所替代;不過,這個類處理起來更容易,因為底層的字符串可以作為屬性來訪問。 *class* `collections.``UserString`(*seq*)模擬一個字符串對象。這個實例對象的內容保存為一個正常字符串,通過 [`UserString`](#collections.UserString "collections.UserString") 的 [`data`](#collections.UserString.data "collections.UserString.data") 屬性存取。實例內容初始化設置為 *seq* 的copy。*seq* 參數可以是任何可通過內建 [`str()`](stdtypes.xhtml#str "str") 函數轉換為字符串的對象。 [`UserString`](#collections.UserString "collections.UserString") 提供了以下屬性作為字符串方法和操作的額外支持: `data`一個真正的 [`str`](stdtypes.xhtml#str "str") 對象用來存放 [`UserString`](#collections.UserString "collections.UserString") 類的內容。 在 3.5 版更改: 新方法 `__getnewargs__`, `__rmod__`, `casefold`, `format_map`, `isprintable`, 和 `maketrans`。 ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](collections.abc.xhtml "collections.abc --- 容器的抽象基類") | - [上一頁](calendar.xhtml "calendar --- General calendar-related functions") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [數據類型](datatypes.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>

                              哎呀哎呀视频在线观看