### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](collections.abc.xhtml "collections.abc --- 容器的抽象基類") |
- [上一頁](calendar.xhtml "calendar --- General calendar-related functions") |
- 
- [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") |
- 
- [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 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec