“Python/docs/3.9/library/collections”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/collections
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:集合 — 容器数据类型 — Python 文档}}
 
<div id="module-collections" class="section">
 
<div id="module-collections" class="section">
  
 
<span id="collections-container-datatypes"></span>
 
<span id="collections-container-datatypes"></span>
= [[#module-collections|<code>collections</code>]] --- Container datatypes =
+
= collections — 容器数据类型 =
  
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/collections/__init__.py Lib/collections/__init__.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/collections/__init__.py`</span>]]
  
This module implements specialized container datatypes providing alternatives to
+
 
Python's general purpose built-in containers, [[../stdtypes#dict|<code>dict</code>]], [[../stdtypes#list|<code>list</code>]],
+
-----
[[../stdtypes#set|<code>set</code>]], and [[../stdtypes#tuple|<code>tuple</code>]].
+
 
 +
该模块实现了专门的容器数据类型,为 Python 的通用内置容器 [[../stdtypes#dict|dict]][[../stdtypes#list|list]][[../stdtypes#set|set]] [[../stdtypes#tuple|tuple]] 提供了替代方案。
  
 
{|
 
{|
 
|width="24%"| [[#collections.namedtuple|<code>namedtuple()</code>]]
 
|width="24%"| [[#collections.namedtuple|<code>namedtuple()</code>]]
|width="76%"| factory function for creating tuple subclasses with named fields
+
|width="76%"| 用于创建具有命名字段的元组子类的工厂函数
 
|-
 
|-
 
| [[#collections.deque|<code>deque</code>]]
 
| [[#collections.deque|<code>deque</code>]]
| list-like container with fast appends and pops on either end
+
| 类似列表的容器,两端具有快速追加和弹出
 
|-
 
|-
 
| [[#collections.ChainMap|<code>ChainMap</code>]]
 
| [[#collections.ChainMap|<code>ChainMap</code>]]
| dict-like class for creating a single view of multiple mappings
+
| 用于创建多个映射的单个视图的类 dict
 
|-
 
|-
 
| [[#collections.Counter|<code>Counter</code>]]
 
| [[#collections.Counter|<code>Counter</code>]]
| dict subclass for counting hashable objects
+
| 用于计算可散列对象的 dict 子类
 
|-
 
|-
 
| [[#collections.OrderedDict|<code>OrderedDict</code>]]
 
| [[#collections.OrderedDict|<code>OrderedDict</code>]]
| dict subclass that remembers the order entries were added
+
| 添加了记住订单条目的 dict 子类
 
|-
 
|-
 
| [[#collections.defaultdict|<code>defaultdict</code>]]
 
| [[#collections.defaultdict|<code>defaultdict</code>]]
| dict subclass that calls a factory function to supply missing values
+
| dict 子类调用工厂函数来提供缺失值
 
|-
 
|-
 
| [[#collections.UserDict|<code>UserDict</code>]]
 
| [[#collections.UserDict|<code>UserDict</code>]]
| wrapper around dictionary objects for easier dict subclassing
+
| 围绕字典对象的包装器,以便于 dict 子类化
 
|-
 
|-
 
| [[#collections.UserList|<code>UserList</code>]]
 
| [[#collections.UserList|<code>UserList</code>]]
| wrapper around list objects for easier list subclassing
+
| 列表对象的包装器,以便于列表子类化
 
|-
 
|-
 
| [[#collections.UserString|<code>UserString</code>]]
 
| [[#collections.UserString|<code>UserString</code>]]
| wrapper around string objects for easier string subclassing
+
| 围绕字符串对象的包装器,以便于字符串子类化
 
|}
 
|}
  
<div class="deprecated-removed">
 
 
<span class="versionmodified">Deprecated since version 3.3, will be removed in version 3.10: </span>Moved [[../collections|<span class="std std-ref">Collections Abstract Base Classes</span>]] to the [[../collections.abc#module-collections|<code>collections.abc</code>]] module.
 
For backwards compatibility, they continue to be visible in this module through
 
Python 3.9.
 
 
 
</div>
 
 
<div id="chainmap-objects" class="section">
 
<div id="chainmap-objects" class="section">
  
== [[#collections.ChainMap|<code>ChainMap</code>]] objects ==
+
== ChainMap 对象 ==
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.3 新版功能.</span>
+
<span class="versionmodified added">3.3 版中的新功能。</span>
  
  
 
</div>
 
</div>
A [[#collections.ChainMap|<code>ChainMap</code>]] class is provided for quickly linking a number of mappings
+
提供了一个 [[#collections.ChainMap|ChainMap]] 类,用于快速链接多个映射,以便将它们视为一个单元。 它通常比创建新字典并运行多个 [[../stdtypes#dict|update()]] 调用快得多。
so they can be treated as a single unit. It is often much faster than creating
 
a new dictionary and running multiple [[../stdtypes#dict|<code>update()</code>]] calls.
 
  
The class can be used to simulate nested scopes and is useful in templating.
+
该类可用于模拟嵌套作用域,并可用于模板化。
  
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>ChainMap</code><span class="sig-paren">(</span>''<span class="o">*</span><span class="n">maps</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">ChainMap</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">maps</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>A [[#collections.ChainMap|<code>ChainMap</code>]] groups multiple dicts or other mappings together to
+
<dd><p>[[#collections.ChainMap|ChainMap]] 将多个字典或其他映射组合在一起以创建单个可更新视图。 如果未指定 ''maps'',则提供单个空字典,以便新链始终具有至少一个映射。</p>
create a single, updateable view. If no ''maps'' are specified, a single empty
+
<p>底层映射存储在一个列表中。 该列表是公开的,可以使用 ''maps'' 属性访问或更新。 没有其他状态。</p>
dictionary is provided so that a new chain always has at least one mapping.</p>
+
<p>查找会连续搜索底层映射,直到找到一个键。 相比之下,写入、更新和删除仅对第一个映射进行操作。</p>
<p>The underlying mappings are stored in a list. That list is public and can
+
<p>[[#collections.ChainMap|ChainMap]] 通过引用合并了底层映射。 因此,如果底层映射之一得到更新,这些更改将反映在 [[#collections.ChainMap|ChainMap]] 中。</p>
be accessed or updated using the ''maps'' attribute. There is no other state.</p>
+
<p>支持所有常用的字典方法。 此外,还有一个 ''maps'' 属性,一个用于创建新子上下文的方法,以及一个用于访问除第一个映射之外的所有映射的属性:</p>
<p>Lookups search the underlying mappings successively until a key is found. In
 
contrast, writes, updates, and deletions only operate on the first mapping.</p>
 
<p>A [[#collections.ChainMap|<code>ChainMap</code>]] incorporates the underlying mappings by reference. So, if
 
one of the underlying mappings gets updated, those changes will be reflected
 
in [[#collections.ChainMap|<code>ChainMap</code>]].</p>
 
<p>All of the usual dictionary methods are supported. In addition, there is a
 
''maps'' attribute, a method for creating new subcontexts, and a property for
 
accessing all but the first mapping:</p>
 
 
<dl>
 
<dl>
<dt><code>maps</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">maps</span></span></dt>
<dd><p>A user updateable list of mappings. The list is ordered from
+
<dd><p>用户可更新的映射列表。 该列表按从第一个搜索到最后一个搜索的顺序排列。 它是唯一的存储状态,可以修改以更改要搜索的映射。 该列表应始终包含至少一个映射。</p></dd></dl>
first-searched to last-searched. It is the only stored state and can
 
be modified to change which mappings are searched. The list should
 
always contain at least one mapping.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>new_child</code><span class="sig-paren">(</span>''<span class="n">m</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">new_child</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">m</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns a new [[#collections.ChainMap|<code>ChainMap</code>]] containing a new map followed by
+
<dd><p>返回一个新的 [[#collections.ChainMap|ChainMap]],其中包含一个新地图,后跟当前实例中的所有地图。 如果指定了 <code>m</code>,则它成为映射列表最前面的新映射; 如果未指定,则使用空字典,因此对 <code>d.new_child()</code> 的调用等效于:<code>ChainMap({}, *d.maps)</code>。 此方法用于创建可以在不更改任何父映射中的值的情况下更新的子上下文。</p>
all of the maps in the current instance. If <code>m</code> is specified,
 
it becomes the new map at the front of the list of mappings; if not
 
specified, an empty dict is used, so that a call to <code>d.new_child()</code>
 
is equivalent to: <code>ChainMap({}, *d.maps)</code>. This method is used for
 
creating subcontexts that can be updated without altering values in any
 
of the parent mappings.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.4 版更改: </span>The optional <code>m</code> parameter was added.</p>
+
<p><span class="versionmodified changed"> 3.4 版更改: </span> 添加了可选的 <code>m</code> 参数。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>parents</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">parents</span></span></dt>
<dd><p>Property returning a new [[#collections.ChainMap|<code>ChainMap</code>]] containing all of the maps in
+
<dd><p>属性返回一个新的 [[#collections.ChainMap|ChainMap]],其中包含当前实例中除第一个之外的所有地图。 这对于跳过搜索中的第一个地图很有用。 用例类似于 [[../../glossary#term-nested-scope|嵌套作用域]] 中使用的 [[../../reference/simple_stmts#nonlocal|nonlocal]] 关键字的用例。 这些用例还与内置 [[../functions#super|super()]] 函数的用例并行。 对 <code>d.parents</code> 的引用相当于:<code>ChainMap(*d.maps[1:])</code></p></dd></dl>
the current instance except the first one. This is useful for skipping
 
the first map in the search. Use cases are similar to those for the
 
[[../../reference/simple_stmts#nonlocal|<code>nonlocal</code>]] keyword used in [[../../glossary#term-nested-scope|<span class="xref std std-term">nested scopes</span>]]. The use cases also parallel those for the built-in
 
[[../functions#super|<code>super()</code>]] function. A reference to <code>d.parents</code> is equivalent to:
 
<code>ChainMap(*d.maps[1:])</code>.</p></dd></dl>
 
  
<p>Note, the iteration order of a [[#collections.ChainMap|<code>ChainMap()</code>]] is determined by
+
<p>注意,[[#collections.ChainMap|ChainMap()]] 的迭代顺序是通过扫描从后到前的映射来确定的:</p>
scanning the mappings last to first:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; baseline = {'music': 'bach', 'art': 'rembrandt'}
+
<syntaxhighlight lang="python3">>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
&gt;&gt;&gt; adjustments = {'art': 'van gogh', 'opera': 'carmen'}
+
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
&gt;&gt;&gt; list(ChainMap(adjustments, baseline))
+
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']</pre>
+
['music', 'art', 'opera']</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>This gives the same ordering as a series of [[../stdtypes#dict|<code>dict.update()</code>]] calls
+
<p>这给出了与从最后一个映射开始的一系列 [[../stdtypes#dict|dict.update()]] 调用相同的顺序:</p>
starting with the last mapping:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; combined = baseline.copy()
+
<syntaxhighlight lang="python3">>>> combined = baseline.copy()
&gt;&gt;&gt; combined.update(adjustments)
+
>>> combined.update(adjustments)
&gt;&gt;&gt; list(combined)
+
>>> list(combined)
['music', 'art', 'opera']</pre>
+
['music', 'art', 'opera']</syntaxhighlight>
  
 
</div>
 
</div>
第139行: 第107行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.9 版更改: </span>Added support for <code>|</code> and <code>|=</code> operators, specified in <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0584 '''PEP 584'''].</p>
+
<p><span class="versionmodified changed"> 3.9 版更改: </span> 添加了对 <code>|</code> <code>|=</code> 运算符的支持,在 <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0584 PEP 584] 中指定。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第145行: 第113行:
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
* The [https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py MultiContext class] in the Enthought [https://github.com/enthought/codetools CodeTools package] has options to support writing to any mapping in the chain.
+
* Enthought [https://github.com/enthought/codetools CodeTools 包] 中的 [https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py MultiContext ] 具有支持写入链中任何映射的选项。
* Django's [https://github.com/django/django/blob/master/django/template/context.py Context class] for templating is a read-only chain of mappings. It also features pushing and popping of contexts similar to the [[#collections.ChainMap.new_child|<code>new_child()</code>]] method and the [[#collections.ChainMap.parents|<code>parents</code>]] property.
+
* Django [https://github.com/django/django/blob/main/django/template/context.py 上下文类] 用于模板化是一个只读的映射链。 它还具有类似于 [[#collections.ChainMap.new_child|new_child()]] 方法和 [[#collections.ChainMap.parents|parents]] 属性的上下文推送和弹出功能。
* The [https://code.activestate.com/recipes/577434/ Nested Contexts recipe] has options to control whether writes and other mutations apply only to the first mapping or to any mapping in the chain.
+
* [https://code.activestate.com/recipes/577434/ 嵌套上下文配方] 具有控制写入和其他更改是仅应用于第一个映射还是链中的任何映射的选项。
* A [https://code.activestate.com/recipes/305268/ greatly simplified read-only version of Chainmap].
+
* 一个 [https://code.activestate.com/recipes/305268/ 大大简化的 Chainmap] 只读版本。
  
  
第156行: 第124行:
 
<div id="chainmap-examples-and-recipes" class="section">
 
<div id="chainmap-examples-and-recipes" class="section">
  
=== [[#collections.ChainMap|<code>ChainMap</code>]] Examples and Recipes ===
+
=== ChainMap 例子和食谱 ===
  
This section shows various approaches to working with chained maps.
+
本节展示了使用链式地图的各种方法。
  
Example of simulating Python's internal lookup chain:
+
模拟Python内部查找链的例子:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第166行: 第134行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import builtins
+
<syntaxhighlight lang="python3">import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))</pre>
+
pylookup = ChainMap(locals(), globals(), vars(builtins))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Example of letting user specified command-line arguments take precedence over
+
让用户指定的命令行参数优先于环境变量的示例,而环境变量又优先于默认值:
environment variables which in turn take precedence over default values:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第179行: 第146行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import os, argparse
+
<syntaxhighlight lang="python3">import os, argparse
  
 
defaults = {'color': 'red', 'user': 'guest'}
 
defaults = {'color': 'red', 'user': 'guest'}
第191行: 第158行:
 
combined = ChainMap(command_line_args, os.environ, defaults)
 
combined = ChainMap(command_line_args, os.environ, defaults)
 
print(combined['color'])
 
print(combined['color'])
print(combined['user'])</pre>
+
print(combined['user'])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Example patterns for using the [[#collections.ChainMap|<code>ChainMap</code>]] class to simulate nested
+
使用 [[#collections.ChainMap|ChainMap]] 类模拟嵌套上下文的示例模式:
contexts:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第203行: 第169行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>c = ChainMap()        # Create root context
+
<syntaxhighlight lang="python3">c = ChainMap()        # Create root context
 
d = c.new_child()    # Create nested child context
 
d = c.new_child()    # Create nested child context
 
e = c.new_child()    # Child of c, independent from d
 
e = c.new_child()    # Child of c, independent from d
第217行: 第183行:
 
len(d)                # Number of nested values
 
len(d)                # Number of nested values
 
d.items()            # All nested items
 
d.items()            # All nested items
dict(d)              # Flatten into a regular dictionary</pre>
+
dict(d)              # Flatten into a regular dictionary</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[#collections.ChainMap|<code>ChainMap</code>]] class only makes updates (writes and deletions) to the
+
[[#collections.ChainMap|ChainMap]] 类只对链中的第一个映射进行更新(写入和删除),而查找将搜索整个链。 但是,如果需要深度写入和删除,很容易创建一个子类来更新链中更深层次的键:
first mapping in the chain while lookups will search the full chain. However,
 
if deep writes and deletions are desired, it is easy to make a subclass that
 
updates keys found deeper in the chain:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第231行: 第194行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class DeepChainMap(ChainMap):
+
<syntaxhighlight lang="python3">class DeepChainMap(ChainMap):
 
     'Variant of ChainMap that allows direct updates to inner scopes'
 
     'Variant of ChainMap that allows direct updates to inner scopes'
  
第248行: 第211行:
 
         raise KeyError(key)
 
         raise KeyError(key)
  
&gt;&gt;&gt; d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'})
+
>>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'})
&gt;&gt;&gt; d['lion'] = 'orange'        # update an existing key two levels down
+
>>> d['lion'] = 'orange'        # update an existing key two levels down
&gt;&gt;&gt; d['snake'] = 'red'          # new keys get added to the topmost dict
+
>>> d['snake'] = 'red'          # new keys get added to the topmost dict
&gt;&gt;&gt; del d['elephant']            # remove an existing key one level down
+
>>> del d['elephant']            # remove an existing key one level down
&gt;&gt;&gt; d                            # display result
+
>>> d                            # display result
DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})</pre>
+
DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})</syntaxhighlight>
  
 
</div>
 
</div>
第264行: 第227行:
 
<div id="counter-objects" class="section">
 
<div id="counter-objects" class="section">
  
== [[#collections.Counter|<code>Counter</code>]] objects ==
+
== 计数器对象 ==
  
A counter tool is provided to support convenient and rapid tallies.
+
提供了一个计数器工具来支持方便和快速的计数。 例如:
For example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第273行: 第235行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; # Tally occurrences of words in a list
+
<syntaxhighlight lang="python3">>>> # Tally occurrences of words in a list
&gt;&gt;&gt; cnt = Counter()
+
>>> cnt = Counter()
&gt;&gt;&gt; for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
+
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
 
...    cnt[word] += 1
 
...    cnt[word] += 1
&gt;&gt;&gt; cnt
+
>>> cnt
 
Counter({'blue': 3, 'red': 2, 'green': 1})
 
Counter({'blue': 3, 'red': 2, 'green': 1})
  
&gt;&gt;&gt; # Find the ten most common words in Hamlet
+
>>> # Find the ten most common words in Hamlet
&gt;&gt;&gt; import re
+
>>> import re
&gt;&gt;&gt; words = re.findall(r'\w+', open('hamlet.txt').read().lower())
+
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
&gt;&gt;&gt; Counter(words).most_common(10)
+
>>> Counter(words).most_common(10)
 
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
  ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]</pre>
+
  ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]</syntaxhighlight>
  
 
</div>
 
</div>
第291行: 第253行:
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>Counter</code><span class="sig-paren">(</span><span class="optional">[</span>''iterable-or-mapping''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">Counter</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">iterable-or-mapping</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>A [[#collections.Counter|<code>Counter</code>]] is a [[../stdtypes#dict|<code>dict</code>]] subclass for counting hashable objects.
+
<dd><p>[[#collections.Counter|Counter]] 是一个 [[../stdtypes#dict|dict]] 子类,用于计算可散列对象。 它是一个集合,其中元素存储为字典键,它们的计数存储为字典值。 计数可以是任何整数值,包括零或负计数。 [[#collections.Counter|Counter]] 类类似于其他语言中的 bag 或 multisets。</p>
It is a collection where elements are stored as dictionary keys
+
<p>元素从 ''可迭代'' 计数或从另一个 ''映射'' (或计数器)初始化:</p>
and their counts are stored as dictionary values. Counts are allowed to be
 
any integer value including zero or negative counts. The [[#collections.Counter|<code>Counter</code>]]
 
class is similar to bags or multisets in other languages.</p>
 
<p>Elements are counted from an ''iterable'' or initialized from another
 
''mapping'' (or counter):</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c = Counter()                          # a new, empty counter
+
<syntaxhighlight lang="python">>>> c = Counter()                          # a new, empty counter
&gt;&gt;&gt; c = Counter('gallahad')                # a new counter from an iterable
+
>>> c = Counter('gallahad')                # a new counter from an iterable
&gt;&gt;&gt; c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
+
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
&gt;&gt;&gt; c = Counter(cats=4, dogs=8)            # a new counter from keyword args</pre>
+
>>> c = Counter(cats=4, dogs=8)            # a new counter from keyword args</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Counter objects have a dictionary interface except that they return a zero
+
<p>Counter 对象有一个字典接口,除了它们为丢失的项目返回零计数而不是引发 [[../exceptions#KeyError|KeyError]]</p>
count for missing items instead of raising a [[../exceptions#KeyError|<code>KeyError</code>]]:</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c = Counter(['eggs', 'ham'])
+
<syntaxhighlight lang="python">>>> c = Counter(['eggs', 'ham'])
&gt;&gt;&gt; c['bacon']                              # count of a missing element is zero
+
>>> c['bacon']                              # count of a missing element is zero
0</pre>
+
0</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Setting a count to zero does not remove an element from a counter.
+
<p>将计数设置为零不会从计数器中删除元素。 使用 <code>del</code> 将其完全删除:</p>
Use <code>del</code> to remove it entirely:</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c['sausage'] = 0                        # counter entry with a zero count
+
<syntaxhighlight lang="python">>>> c['sausage'] = 0                        # counter entry with a zero count
&gt;&gt;&gt; del c['sausage']                        # del actually removes the entry</pre>
+
>>> del c['sausage']                        # del actually removes the entry</syntaxhighlight>
  
 
</div>
 
</div>
第338行: 第293行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.1 新版功能.</span></p>
+
<p><span class="versionmodified added">3.1 版中的新功能。</span></p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.7 版更改: </span>As a [[../stdtypes#dict|<code>dict</code>]] subclass, [[#collections.Counter|<code>Counter</code>]]
+
<p><span class="versionmodified changed"> 3.7 版本变更: </span> 作为 [[../stdtypes#dict|dict]] 子类,[[#collections.Counter|Counter]] 继承了记忆插入顺序的能力。 ''Counter'' 对象上的数学运算也保持顺序。 结果按照在左操作数中首次遇到元素的时间和在右操作数中遇到的顺序进行排序。</p>
Inherited the capability to remember insertion order. Math operations
 
on ''Counter'' objects also preserve order. Results are ordered
 
according to when an element is first encountered in the left operand
 
and then by the order encountered in the right operand.</p>
 
  
 
</div>
 
</div>
<p>Counter objects support three methods beyond those available for all
+
<p>Counter 对象支持三种超出所有字典可用的方法:</p>
dictionaries:</p>
 
 
<dl>
 
<dl>
<dt><code>elements</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">elements</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return an iterator over elements repeating each as many times as its
+
<dd><p>在元素上返回一个迭代器,每个元素的重复次数与其计数相同。 元素按第一次遇到的顺序返回。 如果元素的计数小于 1,则 [[#collections.Counter.elements|elements()]] 将忽略它。</p>
count. Elements are returned in the order first encountered. If an
 
element's count is less than one, [[#collections.Counter.elements|<code>elements()</code>]] will ignore it.</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c = Counter(a=4, b=2, c=0, d=-2)
+
<syntaxhighlight lang="python">>>> c = Counter(a=4, b=2, c=0, d=-2)
&gt;&gt;&gt; sorted(c.elements())
+
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']</pre>
+
['a', 'a', 'a', 'a', 'b', 'b']</syntaxhighlight>
  
 
</div>
 
</div>
第370行: 第318行:
  
 
<dl>
 
<dl>
<dt><code>most_common</code><span class="sig-paren">(</span><span class="optional">[</span>''n''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">most_common</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">n</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return a list of the ''n'' most common elements and their counts from the
+
<dd><p>返回 ''n'' 最常见元素的列表及其从最常见到最少的计数。 如果省略 ''n'' <code>None</code>,则 [[#collections.Counter.most_common|most_common()]] 返回计数器中的 ''all'' 元素。 具有相等计数的元素按第一次遇到的顺序排序:</p>
most common to the least. If ''n'' is omitted or <code>None</code>,
 
[[#collections.Counter.most_common|<code>most_common()</code>]] returns ''all'' elements in the counter.
 
Elements with equal counts are ordered in the order first encountered:</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Counter('abracadabra').most_common(3)
+
<syntaxhighlight lang="python">>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]</pre>
+
[('a', 5), ('b', 2), ('r', 2)]</syntaxhighlight>
  
 
</div>
 
</div>
第387行: 第332行:
  
 
<dl>
 
<dl>
<dt><code>subtract</code><span class="sig-paren">(</span><span class="optional">[</span>''iterable-or-mapping''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">subtract</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">iterable-or-mapping</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Elements are subtracted from an ''iterable'' or from another ''mapping''
+
<dd><p>''可迭代'' 或另一个 ''映射'' (或计数器)中减去元素。 像 [[../stdtypes#dict|dict.update()]] 但减去计数而不是替换它们。 输入和输出都可以为零或负。</p>
(or counter). Like [[../stdtypes#dict|<code>dict.update()</code>]] but subtracts counts instead
 
of replacing them. Both inputs and outputs may be zero or negative.</p>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c = Counter(a=4, b=2, c=0, d=-2)
+
<syntaxhighlight lang="python">>>> c = Counter(a=4, b=2, c=0, d=-2)
&gt;&gt;&gt; d = Counter(a=1, b=2, c=3, d=4)
+
>>> d = Counter(a=1, b=2, c=3, d=4)
&gt;&gt;&gt; c.subtract(d)
+
>>> c.subtract(d)
&gt;&gt;&gt; c
+
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})</pre>
+
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})</syntaxhighlight>
  
 
</div>
 
</div>
第406行: 第349行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.2 新版功能.</span></p>
+
<p><span class="versionmodified added">3.2 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
<p>The usual dictionary methods are available for [[#collections.Counter|<code>Counter</code>]] objects
+
<p>通常的字典方法可用于 [[#collections.Counter|Counter]] 对象,除了两个对计数器的工作方式不同。</p>
except for two which work differently for counters.</p>
 
 
<dl>
 
<dl>
<dt><code>fromkeys</code><span class="sig-paren">(</span>''<span class="n">iterable</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">fromkeys</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">iterable</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>This class method is not implemented for [[#collections.Counter|<code>Counter</code>]] objects.</p></dd></dl>
+
<dd><p>此类方法未为 [[#collections.Counter|Counter]] 对象实现。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>update</code><span class="sig-paren">(</span><span class="optional">[</span>''iterable-or-mapping''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">update</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">iterable-or-mapping</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Elements are counted from an ''iterable'' or added-in from another
+
<dd><p>元素从 ''可迭代'' 计数或从另一个 ''映射'' (或计数器)添加。 像 [[../stdtypes#dict|dict.update()]] 但增加计数而不是替换它们。 此外,''iterable'' 应该是一个元素序列,而不是一个 <code>(key, value)</code> 对序列。</p></dd></dl>
''mapping'' (or counter). Like [[../stdtypes#dict|<code>dict.update()</code>]] but adds counts
 
instead of replacing them. Also, the ''iterable'' is expected to be a
 
sequence of elements, not a sequence of <code>(key, value)</code> pairs.</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
Common patterns for working with [[#collections.Counter|<code>Counter</code>]] objects:
+
使用 [[#collections.Counter|Counter]] 对象的常见模式:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第430行: 第369行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>sum(c.values())                # total of all counts
+
<syntaxhighlight lang="python3">sum(c.values())                # total of all counts
 
c.clear()                      # reset all counts
 
c.clear()                      # reset all counts
 
list(c)                        # list unique elements
 
list(c)                        # list unique elements
第438行: 第377行:
 
Counter(dict(list_of_pairs))    # convert from 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.most_common()[:-n-1:-1]      # n least common elements
+c                              # remove zero and negative counts</pre>
+
+c                              # remove zero and negative counts</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Several mathematical operations are provided for combining [[#collections.Counter|<code>Counter</code>]]
+
提供了几种数学运算来组合 [[#collections.Counter|Counter]] 对象以生成多重集(计数大于零的计数器)。 加法和减法通过增加或减去相应元素的计数来组合计数器。 交集和并集返回对应计数的最小值和最大值。 每个操作都可以接受带符号计数的输入,但输出将排除计数为零或更少的结果。
objects to produce multisets (counters that have counts greater than zero).
 
Addition and subtraction combine counters by adding or subtracting the counts
 
of corresponding elements. Intersection and union return the minimum and
 
maximum of corresponding counts. Each operation can accept inputs with signed
 
counts, but the output will exclude results with counts of zero or less.
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第454行: 第388行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c = Counter(a=3, b=1)
+
<syntaxhighlight lang="python">>>> c = Counter(a=3, b=1)
&gt;&gt;&gt; d = Counter(a=1, b=2)
+
>>> d = Counter(a=1, b=2)
&gt;&gt;&gt; c + d                      # add two counters together:  c[x] + d[x]
+
>>> c + d                      # add two counters together:  c[x] + d[x]
 
Counter({'a': 4, 'b': 3})
 
Counter({'a': 4, 'b': 3})
&gt;&gt;&gt; c - d                      # subtract (keeping only positive counts)
+
>>> c - d                      # subtract (keeping only positive counts)
 
Counter({'a': 2})
 
Counter({'a': 2})
&gt;&gt;&gt; c &amp; d                      # intersection:  min(c[x], d[x])  
+
>>> c & d                      # intersection:  min(c[x], d[x])  
 
Counter({'a': 1, 'b': 1})
 
Counter({'a': 1, 'b': 1})
&gt;&gt;&gt; c | d                      # union:  max(c[x], d[x])
+
>>> c | d                      # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})</pre>
+
Counter({'a': 3, 'b': 2})</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Unary addition and subtraction are shortcuts for adding an empty counter
+
一元加法和减法是添加空计数器或从空计数器中减去的快捷方式。
or subtracting from an empty counter.
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第475行: 第408行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; c = Counter(a=2, b=-4)
+
<syntaxhighlight lang="python">>>> c = Counter(a=2, b=-4)
&gt;&gt;&gt; +c
+
>>> +c
 
Counter({'a': 2})
 
Counter({'a': 2})
&gt;&gt;&gt; -c
+
>>> -c
Counter({'b': 4})</pre>
+
Counter({'b': 4})</syntaxhighlight>
  
 
</div>
 
</div>
第486行: 第419行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.3 新版功能: </span>Added support for unary plus, unary minus, and in-place multiset operations.
+
<span class="versionmodified added"> 3.3 新功能: </span> 增加了对一元加、一元减和就地多集操作的支持。
  
  
第492行: 第425行:
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
Counters were primarily designed to work with positive integers to represent
+
计数器主要设计为使用正整数来表示运行计数; 但是,注意不要不必要地排除需要其他类型或负值的用例。 为了帮助处理这些用例,本节记录了最小范围和类型限制。
running counts; however, care was taken to not unnecessarily preclude use
 
cases needing other types or negative values. To help with those use cases,
 
this section documents the minimum range and type restrictions.
 
  
* The [[#collections.Counter|<code>Counter</code>]] class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you ''could'' store anything in the value field.
+
* [[#collections.Counter|Counter]] 类本身是一个字典子类,对其键和值没有限制。 这些值旨在是表示计数的数字,但您 ''可以'' 在值字段中存储任何内容。
* The [[#collections.Counter.most_common|<code>most_common()</code>]] method requires only that the values be orderable.
+
* [[#collections.Counter.most_common|most_common()]] 方法只要求值是可排序的。
* For in-place operations such as <code>c[key] += 1</code>, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for [[#collections.Counter.update|<code>update()</code>]] and [[#collections.Counter.subtract|<code>subtract()</code>]] which allow negative and zero values for both inputs and outputs.
+
* 对于<code>c[key] += 1</code>等就地操作,值类型只需要支持加减。 因此分数、浮点数和小数都可以使用,并且支持负值。 [[#collections.Counter.update|update()]] [[#collections.Counter.subtract|subtract()]] 也是如此,它们允许输入和输出的负值和零值。
* The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.
+
* 多集方法仅适用于具有正值的用例。 输入可能是负数或零,但只会创建具有正值的输出。 没有类型限制,但是值类型需要支持加减比较。
* The [[#collections.Counter.elements|<code>elements()</code>]] method requires integer counts. It ignores zero and negative counts.
+
* [[#collections.Counter.elements|elements()]] 方法需要整数计数。 它忽略零和负计数。
  
  
第509行: 第439行:
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
 
<ul>
 
<ul>
<li><p>[https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html Bag class]
+
<li><p>[https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html Smalltalk 中的包类] </p></li>
in Smalltalk.</p></li>
+
<li><p>[https://en.wikipedia.org/wiki/Multiset Multisets] 的维基百科条目。</p></li>
<li><p>Wikipedia entry for [https://en.wikipedia.org/wiki/Multiset Multisets].</p></li>
+
<li><p>[http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm C++ multisets] 教程示例。</p></li>
<li><p>[http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm C++ multisets]
+
<li><p>有关多重集及其用例的数学运算,请参阅克努斯,唐纳德。 计算机编程艺术第二卷,第 4.6.3 节,练习 19 .</p></li>
tutorial with examples.</p></li>
+
<li><p>要枚举给定元素集上给定大小的所有不同多重集,请参阅 [[../itertools#itertools|itertools.combinations_with_replacement()]]</p>
<li><p>For mathematical operations on multisets and their use cases, see
 
''Knuth, Donald. The Art of Computer Programming Volume II,
 
Section 4.6.3, Exercise 19''.</p></li>
 
<li><p>To enumerate all distinct multisets of a given size over a given set of
 
elements, see [[../itertools#itertools|<code>itertools.combinations_with_replacement()</code>]]:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>map(Counter, combinations_with_replacement('ABC', 2)) # --&gt; AA AB AC BB BC CC</pre>
+
<syntaxhighlight lang="python3">map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC</syntaxhighlight>
  
 
</div>
 
</div>
第538行: 第463行:
 
<div id="deque-objects" class="section">
 
<div id="deque-objects" class="section">
  
== [[#collections.deque|<code>deque</code>]] objects ==
+
== deque 对象 ==
  
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>deque</code><span class="sig-paren">(</span><span class="optional">[</span>''iterable''<span class="optional">[</span>, ''maxlen''<span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">deque</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">iterable</span>''<span class="optional">[</span>, ''<span class="pre">maxlen</span>''<span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a new deque object initialized left-to-right (using [[#collections.deque.append|<code>append()</code>]]) with
+
<dd><p>返回一个从左到右初始化的新 deque 对象(使用 [[#collections.deque.append|append()]]),数据来自 ''iterable''。 如果未指定 ''iterable'',则新的双端队列为空。</p>
data from ''iterable''. If ''iterable'' is not specified, the new deque is empty.</p>
+
<p>双端队列是栈和队列的泛化(名称发音为“deck”,是“双端队列”的缩写)。 双端队列支持线程安全、内存高效的追加和从双端队列的任一侧弹出,在任一方向上的 O(1) 性能大致相同。</p>
<p>Deques are a generalization of stacks and queues (the name is pronounced &quot;deck&quot;
+
<p>尽管 [[../stdtypes#list|list]] 对象支持类似的操作,但它们针对快速固定长度的操作进行了优化,并为 <code>pop(0)</code> <code>insert(0, v)</code> 操作产生 O(n) 内存移动成本,这改变了底层数据表示的大小和位置。</p>
and is short for &quot;double-ended queue&quot;). Deques support thread-safe, memory
+
<p>如果未指定 ''maxlen'' <code>None</code>,则双端队列可能会增长到任意长度。 否则,双端队列受限于指定的最大长度。 一旦有界长度的双端队列已满,当添加新项目时,从另一端丢弃相应数量的项目。 有界长度的双端队列提供类似于 Unix 中的 <code>tail</code> 过滤器的功能。 它们还可用于跟踪仅对最近的活动感兴趣的交易和其他数据池。</p>
efficient appends and pops from either side of the deque with approximately the
+
<p>Deque 对象支持以下方法:</p>
same O(1) performance in either direction.</p>
 
<p>Though [[../stdtypes#list|<code>list</code>]] objects support similar operations, they are optimized for
 
fast fixed-length operations and incur O(n) memory movement costs for
 
<code>pop(0)</code> and <code>insert(0, v)</code> operations which change both the size and
 
position of the underlying data representation.</p>
 
<p>If ''maxlen'' is not specified or is <code>None</code>, deques may grow to an
 
arbitrary length. Otherwise, the deque is bounded to the specified maximum
 
length. Once a bounded length deque is full, when new items are added, a
 
corresponding number of items are discarded from the opposite end. Bounded
 
length deques provide functionality similar to the <code>tail</code> filter in
 
Unix. They are also useful for tracking transactions and other pools of data
 
where only the most recent activity is of interest.</p>
 
<p>Deque objects support the following methods:</p>
 
 
<dl>
 
<dl>
<dt><code>append</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">append</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Add ''x'' to the right side of the deque.</p></dd></dl>
+
<dd><p>''x'' 添加到双端队列的右侧。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>appendleft</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">appendleft</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Add ''x'' to the left side of the deque.</p></dd></dl>
+
<dd><p>''x'' 添加到双端队列的左侧。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">clear</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Remove all elements from the deque leaving it with length 0.</p></dd></dl>
+
<dd><p>从双端队列中删除所有元素,使其长度为 0。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">copy</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Create a shallow copy of the deque.</p>
+
<dd><p>创建双端队列的浅拷贝。</p>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.5 新版功能.</span></p>
+
<p><span class="versionmodified added">3.5 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>count</code><span class="sig-paren">(</span>''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">count</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Count the number of deque elements equal to ''x''.</p>
+
<dd><p>计算等于 ''x'' 的双端队列元素的数量。</p>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.2 新版功能.</span></p>
+
<p><span class="versionmodified added">3.2 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>extend</code><span class="sig-paren">(</span>''<span class="n">iterable</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">extend</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">iterable</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Extend the right side of the deque by appending elements from the iterable
+
<dd><p>通过附加来自可迭代参数的元素来扩展双端队列的右侧。</p></dd></dl>
argument.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>extendleft</code><span class="sig-paren">(</span>''<span class="n">iterable</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">extendleft</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">iterable</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Extend the left side of the deque by appending elements from ''iterable''.
+
<dd><p>通过附加来自 ''iterable'' 的元素来扩展双端队列的左侧。 请注意,一系列左追加会导致可迭代参数中元素的顺序颠倒。</p></dd></dl>
Note, the series of left appends results in reversing the order of
 
elements in the iterable argument.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>index</code><span class="sig-paren">(</span>''x''<span class="optional">[</span>, ''start''<span class="optional">[</span>, ''stop''<span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">index</span></span><span class="sig-paren">(</span>''<span class="pre">x</span>''<span class="optional">[</span>, ''<span class="pre">start</span>''<span class="optional">[</span>, ''<span class="pre">stop</span>''<span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return the position of ''x'' in the deque (at or after index ''start''
+
<dd><p>返回 ''x'' 在双端队列中的位置(在索引 ''start'' 处或之后和索引 ''stop'' 之前)。 如果未找到,则返回第一个匹配项或引发 [[../exceptions#ValueError|ValueError]]</p>
and before index ''stop''). Returns the first match or raises
 
[[../exceptions#ValueError|<code>ValueError</code>]] if not found.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.5 新版功能.</span></p>
+
<p><span class="versionmodified added">3.5 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>insert</code><span class="sig-paren">(</span>''<span class="n">i</span>'', ''<span class="n">x</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">insert</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">i</span></span>'', ''<span class="n"><span class="pre">x</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Insert ''x'' into the deque at position ''i''.</p>
+
<dd><p>''x'' 插入双端队列中的位置 ''i''</p>
<p>If the insertion would cause a bounded deque to grow beyond ''maxlen'',
+
<p>如果插入会导致有界双端队列增长超过 ''maxlen'',则会引发 [[../exceptions#IndexError|IndexError]]</p>
an [[../exceptions#IndexError|<code>IndexError</code>]] is raised.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.5 新版功能.</span></p>
+
<p><span class="versionmodified added">3.5 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">pop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Remove and return an element from the right side of the deque. If no
+
<dd><p>从双端队列的右侧移除并返回一个元素。 如果不存在元素,则引发 [[../exceptions#IndexError|IndexError]]</p></dd></dl>
elements are present, raises an [[../exceptions#IndexError|<code>IndexError</code>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>popleft</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">popleft</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Remove and return an element from the left side of the deque. If no
+
<dd><p>从双端队列的左侧移除并返回一个元素。 如果不存在元素,则引发 [[../exceptions#IndexError|IndexError]]</p></dd></dl>
elements are present, raises an [[../exceptions#IndexError|<code>IndexError</code>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>remove</code><span class="sig-paren">(</span>''<span class="n">value</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">remove</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">value</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Remove the first occurrence of ''value''. If not found, raises a
+
<dd><p>删除第一次出现的 '''' 。 如果未找到,则引发 [[../exceptions#ValueError|ValueError]]</p></dd></dl>
[[../exceptions#ValueError|<code>ValueError</code>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">reverse</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Reverse the elements of the deque in-place and then return <code>None</code>.</p>
+
<dd><p>原地反转双端队列的元素,然后返回 <code>None</code></p>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.2 新版功能.</span></p>
+
<p><span class="versionmodified added">3.2 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>rotate</code><span class="sig-paren">(</span>''<span class="n">n</span><span class="o">=</span><span class="default_value">1</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">rotate</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">n</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Rotate the deque ''n'' steps to the right. If ''n'' is negative, rotate
+
<dd><p>向右旋转双端队列 ''n'' 步。 如果 ''n'' 为负,则向左旋转。</p>
to the left.</p>
+
<p>当双端队列不为空时,向右旋转一级相当于<code>d.appendleft(d.pop())</code>,向左旋转一级相当于<code>d.append(d.popleft())</code></p></dd></dl>
<p>When the deque is not empty, rotating one step to the right is equivalent
 
to <code>d.appendleft(d.pop())</code>, and rotating one step to the left is
 
equivalent to <code>d.append(d.popleft())</code>.</p></dd></dl>
 
  
<p>Deque objects also provide one read-only attribute:</p>
+
<p>Deque 对象还提供了一个只读属性:</p>
 
<dl>
 
<dl>
<dt><code>maxlen</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">maxlen</span></span></dt>
<dd><p>Maximum size of a deque or <code>None</code> if unbounded.</p>
+
<dd><p>双端队列的最大大小或 <code>None</code> 如果无界。</p>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.1 新版功能.</span></p>
+
<p><span class="versionmodified added">3.1 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
 
</dd></dl>
 
</dd></dl>
  
In addition to the above, deques support iteration, pickling, <code>len(d)</code>,
+
除上述之外,双端队列支持迭代、酸洗、<code>len(d)</code><code>reversed(d)</code><code>copy.copy(d)</code><code>copy.deepcopy(d)</code>[[../../reference/expressions#in|in]]的成员资格测试] 运算符和下标引用(例如 <code>d[0]</code>)来访问第一个元素。 索引访问在两端都是 O(1),但在中间变慢到 O(n)。 对于快速随机访问,请改用列表。
<code>reversed(d)</code>, <code>copy.copy(d)</code>, <code>copy.deepcopy(d)</code>, membership testing with
 
the [[../../reference/expressions#in|<code>in</code>]] operator, and subscript references such as <code>d[0]</code> to access
 
the first element. Indexed access is O(1) at both ends but slows to O(n) in
 
the middle. For fast random access, use lists instead.
 
  
Starting in version 3.5, deques support <code>__add__()</code>, <code>__mul__()</code>,
+
3.5 版开始,双端队列支持 <code>__add__()</code><code>__mul__()</code> <code>__imul__()</code>
and <code>__imul__()</code>.
 
  
Example:
+
例子:
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第681行: 第576行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; from collections import deque
+
<pre class="pycon3">&gt;&gt;&gt; from collections import deque
 
&gt;&gt;&gt; d = deque('ghi')                # make a new deque with three items
 
&gt;&gt;&gt; d = deque('ghi')                # make a new deque with three items
 
&gt;&gt;&gt; for elem in d:                  # iterate over the deque's elements
 
&gt;&gt;&gt; for elem in d:                  # iterate over the deque's elements
第737行: 第632行:
 
<div id="deque-recipes" class="section">
 
<div id="deque-recipes" class="section">
  
=== [[#collections.deque|<code>deque</code>]] Recipes ===
+
=== deque 食谱 ===
  
This section shows various approaches to working with deques.
+
本节展示了使用双端队列的各种方法。
  
Bounded length deques provide functionality similar to the <code>tail</code> filter
+
有界长度的双端队列提供类似于 Unix 中的 <code>tail</code> 过滤器的功能:
in Unix:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第748行: 第642行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def tail(filename, n=10):
+
<syntaxhighlight lang="python3">def tail(filename, n=10):
 
     'Return the last n lines of a file'
 
     'Return the last n lines of a file'
 
     with open(filename) as f:
 
     with open(filename) as f:
         return deque(f, n)</pre>
+
         return deque(f, n)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Another approach to using deques is to maintain a sequence of recently
+
使用双端队列的另一种方法是通过添加到右侧并从左侧弹出来维护最近添加的元素序列:
added elements by appending to the right and popping to the left:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第763行: 第656行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def moving_average(iterable, n=3):
+
<syntaxhighlight lang="python3">def moving_average(iterable, n=3):
     # moving_average([40, 30, 50, 46, 39, 44]) --&gt; 40.0 42.0 45.0 43.0
+
     # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
 
     # http://en.wikipedia.org/wiki/Moving_average
 
     # http://en.wikipedia.org/wiki/Moving_average
 
     it = iter(iterable)
 
     it = iter(iterable)
第773行: 第666行:
 
         s += elem - d.popleft()
 
         s += elem - d.popleft()
 
         d.append(elem)
 
         d.append(elem)
         yield s / n</pre>
+
         yield s / n</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
A [https://en.wikipedia.org/wiki/Round-robin_scheduling round-robin scheduler] can be implemented with
+
[https://en.wikipedia.org/wiki/Round-robin_scheduling 循环调度器]可以用存储在[[#collections.deque|deque]]中的输入迭代器来实现。 值是从位置零的活动迭代器产生的。 如果该迭代器耗尽,则可以使用 [[#collections.deque.popleft|popleft()]] 将其删除; 否则,可以使用 [[#collections.deque.rotate|rotate()]] 方法循环回到最后:
input iterators stored in a [[#collections.deque|<code>deque</code>]]. Values are yielded from the active
 
iterator in position zero. If that iterator is exhausted, it can be removed
 
with [[#collections.deque.popleft|<code>popleft()</code>]]; otherwise, it can be cycled back to the end with
 
the [[#collections.deque.rotate|<code>rotate()</code>]] method:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第788行: 第677行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def roundrobin(*iterables):
+
<syntaxhighlight lang="python3">def roundrobin(*iterables):
     &quot;roundrobin('ABC', 'D', 'EF') --&gt; A D E B F C&quot;
+
     "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
 
     iterators = deque(map(iter, iterables))
 
     iterators = deque(map(iter, iterables))
 
     while iterators:
 
     while iterators:
第798行: 第687行:
 
         except StopIteration:
 
         except StopIteration:
 
             # Remove an exhausted iterator.
 
             # Remove an exhausted iterator.
             iterators.popleft()</pre>
+
             iterators.popleft()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[#collections.deque.rotate|<code>rotate()</code>]] method provides a way to implement [[#collections.deque|<code>deque</code>]] slicing and
+
[[#collections.deque.rotate|rotate()]] 方法提供了一种实现 [[#collections.deque|deque]] 切片和删除的方法。 例如,<code>del d[n]</code> 的纯 Python 实现依赖于 <code>rotate()</code> 方法来定位要弹出的元素:
deletion. For example, a pure Python implementation of <code>del d[n]</code> relies on
 
the <code>rotate()</code> method to position elements to be popped:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第811行: 第698行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def delete_nth(d, n):
+
<syntaxhighlight lang="python3">def delete_nth(d, n):
 
     d.rotate(-n)
 
     d.rotate(-n)
 
     d.popleft()
 
     d.popleft()
     d.rotate(n)</pre>
+
     d.rotate(n)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
To implement [[#collections.deque|<code>deque</code>]] slicing, use a similar approach applying
+
要实现 [[#collections.deque|deque]] 切片,请使用类似的方法应用 [[#collections.deque.rotate|rotate()]] 将目标元素带到双端队列的左侧。 使用 [[#collections.deque.popleft|popleft()]] 删除旧条目,使用 [[#collections.deque.extend|extend()]] 添加新条目,然后反向旋转。 通过对该方法的微小改动,很容易实现 Forth 风格的堆栈操作,例如 <code>dup</code><code>drop</code><code>swap</code><code>over</code>、[ X152X]、<code>rot</code> <code>roll</code>
[[#collections.deque.rotate|<code>rotate()</code>]] to bring a target element to the left side of the deque. Remove
 
old entries with [[#collections.deque.popleft|<code>popleft()</code>]], add new entries with [[#collections.deque.extend|<code>extend()</code>]], and then
 
reverse the rotation.
 
With minor variations on that approach, it is easy to implement Forth style
 
stack manipulations such as <code>dup</code>, <code>drop</code>, <code>swap</code>, <code>over</code>, <code>pick</code>,
 
<code>rot</code>, and <code>roll</code>.
 
  
  
第833行: 第714行:
 
<div id="defaultdict-objects" class="section">
 
<div id="defaultdict-objects" class="section">
  
== [[#collections.defaultdict|<code>defaultdict</code>]] objects ==
+
== defaultdict 对象 ==
  
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>defaultdict</code><span class="sig-paren">(</span><span class="optional">[</span>''default_factory''<span class="optional">[</span>, ''...''<span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">defaultdict</span></span><span class="sig-paren">(</span>''<span class="pre">default_factory=None</span>'', ''<span class="pre">/</span>''<span class="optional">[</span>, ''<span class="pre">...</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a new dictionary-like object. [[#collections.defaultdict|<code>defaultdict</code>]] is a subclass of the
+
<dd><p>返回一个新的类似字典的对象。 [[#collections.defaultdict|defaultdict]] 是内置的 [[../stdtypes#dict|dict]] 类的子类。 它覆盖了一种方法并添加了一个可写的实例变量。 其余功能与 [[../stdtypes#dict|dict]] 类相同,此处未记录。</p>
built-in [[../stdtypes#dict|<code>dict</code>]] class. It overrides one method and adds one writable
+
<p>第一个参数提供 [[#collections.defaultdict.default_factory|default_factory]] 属性的初始值; 默认为 <code>None</code>。 所有剩余的参数都被视为传递给 [[../stdtypes#dict|dict]] 构造函数,包括关键字参数。</p>
instance variable. The remaining functionality is the same as for the
+
<p>[[#collections.defaultdict|defaultdict]] 对象除了标准的 [[../stdtypes#dict|dict]] 操作之外还支持以下方法:</p>
[[../stdtypes#dict|<code>dict</code>]] class and is not documented here.</p>
 
<p>The first argument provides the initial value for the [[#collections.defaultdict.default_factory|<code>default_factory</code>]]
 
attribute; it defaults to <code>None</code>. All remaining arguments are treated the same
 
as if they were passed to the [[../stdtypes#dict|<code>dict</code>]] constructor, including keyword
 
arguments.</p>
 
<p>[[#collections.defaultdict|<code>defaultdict</code>]] objects support the following method in addition to the
 
standard [[../stdtypes#dict|<code>dict</code>]] operations:</p>
 
 
<dl>
 
<dl>
<dt><code>__missing__</code><span class="sig-paren">(</span>''<span class="n">key</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">__missing__</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">key</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>If the [[#collections.defaultdict.default_factory|<code>default_factory</code>]] attribute is <code>None</code>, this raises a
+
<dd><p>如果 [[#collections.defaultdict.default_factory|default_factory]] 属性为 <code>None</code>,则会引发 [[../exceptions#KeyError|KeyError]] 异常,并以 ''key'' 作为参数。</p>
[[../exceptions#KeyError|<code>KeyError</code>]] exception with the ''key'' as argument.</p>
+
<p>如果 [[#collections.defaultdict.default_factory|default_factory]] 不是 <code>None</code>,则不带参数调用它以提供给定 ''key'' 的默认值,该值被插入到 ''的字典中键'',并返回。</p>
<p>If [[#collections.defaultdict.default_factory|<code>default_factory</code>]] is not <code>None</code>, it is called without arguments
+
<p>如果调用 [[#collections.defaultdict.default_factory|default_factory]] 引发异常,则此异常将保持不变地传播。</p>
to provide a default value for the given ''key'', this value is inserted in
+
<p>当找不到请求的key时,该方法会被[[../stdtypes#dict|dict]]类的<code>__getitem__()</code>方法调用; 无论它返回或引发什么,然后由 <code>__getitem__()</code> 返回或引发。</p>
the dictionary for the ''key'', and returned.</p>
+
<p>请注意,[[#collections.defaultdict.__missing__|__missing__()]] 不是 ''不是'' 调用除 <code>__getitem__()</code> 之外的任何操作。 这意味着 <code>get()</code> 将像普通字典一样返回 <code>None</code> 作为默认值,而不是使用 [[#collections.defaultdict.default_factory|default_factory]]</p></dd></dl>
<p>If calling [[#collections.defaultdict.default_factory|<code>default_factory</code>]] raises an exception this exception is
 
propagated unchanged.</p>
 
<p>This method is called by the <code>__getitem__()</code> method of the
 
[[../stdtypes#dict|<code>dict</code>]] class when the requested key is not found; whatever it
 
returns or raises is then returned or raised by <code>__getitem__()</code>.</p>
 
<p>Note that [[#collections.defaultdict.__missing__|<code>__missing__()</code>]] is ''not'' called for any operations besides
 
<code>__getitem__()</code>. This means that <code>get()</code> will, like normal
 
dictionaries, return <code>None</code> as a default rather than using
 
[[#collections.defaultdict.default_factory|<code>default_factory</code>]].</p></dd></dl>
 
  
<p>[[#collections.defaultdict|<code>defaultdict</code>]] objects support the following instance variable:</p>
+
<p>[[#collections.defaultdict|defaultdict]] 对象支持以下实例变量:</p>
 
<dl>
 
<dl>
<dt><code>default_factory</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">default_factory</span></span></dt>
<dd><p>This attribute is used by the [[#collections.defaultdict.__missing__|<code>__missing__()</code>]] method; it is
+
<dd><p>该属性由 [[#collections.defaultdict.__missing__|__missing__()]] 方法使用; 它从构造函数的第一个参数(如果存在)或 <code>None</code>(如果不存在)初始化。</p></dd></dl>
initialized from the first argument to the constructor, if present, or to
 
<code>None</code>, if absent.</p></dd></dl>
 
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.9 版更改: </span>Added merge (<code>|</code>) and update (<code>|=</code>) operators, specified in
+
<p><span class="versionmodified changed"> 3.9 版更改: </span> 添加了合并 (<code>|</code>) 和更新 (<code>|=</code>) 运算符,在 <span id="index-1" class="target"></span>[https://www.python.org/dev/peps/pep-0584 PEP 584] 中指定。</p>
<span id="index-1" class="target"></span>[https://www.python.org/dev/peps/pep-0584 '''PEP 584'''].</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第880行: 第742行:
 
<div id="defaultdict-examples" class="section">
 
<div id="defaultdict-examples" class="section">
  
=== [[#collections.defaultdict|<code>defaultdict</code>]] Examples ===
+
=== defaultdict 示例 ===
  
Using [[../stdtypes#list|<code>list</code>]] as the [[#collections.defaultdict.default_factory|<code>default_factory</code>]], it is easy to group a
+
使用 [[../stdtypes#list|list]] 作为 [[#collections.defaultdict.default_factory|default_factory]],可以很容易地将键值对序列分组到列表字典中:
sequence of key-value pairs into a dictionary of lists:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第889行: 第750行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
+
<syntaxhighlight lang="python">>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
&gt;&gt;&gt; d = defaultdict(list)
+
>>> d = defaultdict(list)
&gt;&gt;&gt; for k, v in s:
+
>>> for k, v in s:
 
...    d[k].append(v)
 
...    d[k].append(v)
 
...
 
...
&gt;&gt;&gt; sorted(d.items())
+
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]</pre>
+
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
When each key is encountered for the first time, it is not already in the
+
第一次遇到每个键时,它尚未在映射中; 因此使用 [[#collections.defaultdict.default_factory|default_factory]] 函数自动创建一个条目,该函数返回一个空的 [[../stdtypes#list|列表]] <code>list.append()</code> 操作然后将该值附加到新列表。 当再次遇到键时,查找将正常进行(返回该键的列表)并且 <code>list.append()</code> 操作将另一个值添加到列表中。 这种技术比使用 [[../stdtypes#dict|dict.setdefault()]] 的等效技术更简单、更快:
mapping; so an entry is automatically created using the [[#collections.defaultdict.default_factory|<code>default_factory</code>]]
 
function which returns an empty [[../stdtypes#list|<code>list</code>]]. The <code>list.append()</code>
 
operation then attaches the value to the new list. When keys are encountered
 
again, the look-up proceeds normally (returning the list for that key) and the
 
<code>list.append()</code> operation adds another value to the list. This technique is
 
simpler and faster than an equivalent technique using [[../stdtypes#dict|<code>dict.setdefault()</code>]]:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第912行: 第767行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; d = {}
+
<syntaxhighlight lang="python">>>> d = {}
&gt;&gt;&gt; for k, v in s:
+
>>> for k, v in s:
 
...    d.setdefault(k, []).append(v)
 
...    d.setdefault(k, []).append(v)
 
...
 
...
&gt;&gt;&gt; sorted(d.items())
+
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]</pre>
+
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Setting the [[#collections.defaultdict.default_factory|<code>default_factory</code>]] to [[../functions#int|<code>int</code>]] makes the
+
[[#collections.defaultdict.default_factory|default_factory]] 设置为 [[../functions#int|int]] 使 [[#collections.defaultdict|defaultdict]] 可用于计数(如其他语言中的包或多重集):
[[#collections.defaultdict|<code>defaultdict</code>]] useful for counting (like a bag or multiset in other
 
languages):
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第930行: 第783行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; s = 'mississippi'
+
<syntaxhighlight lang="python">>>> s = 'mississippi'
&gt;&gt;&gt; d = defaultdict(int)
+
>>> d = defaultdict(int)
&gt;&gt;&gt; for k in s:
+
>>> for k in s:
 
...    d[k] += 1
 
...    d[k] += 1
 
...
 
...
&gt;&gt;&gt; sorted(d.items())
+
>>> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]</pre>
+
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
When a letter is first encountered, it is missing from the mapping, so the
+
当第一次遇到字母时,它从映射中丢失,因此 [[#collections.defaultdict.default_factory|default_factory]] 函数调用 [[../functions#int|int()]] 以提供默认计数为零。 增量操作然后建立每个字母的计数。
[[#collections.defaultdict.default_factory|<code>default_factory</code>]] function calls [[../functions#int|<code>int()</code>]] to supply a default count of
 
zero. The increment operation then builds up the count for each letter.
 
  
The function [[../functions#int|<code>int()</code>]] which always returns zero is just a special case of
+
总是返回零的函数 [[../functions#int|int()]] 只是常量函数的一个特例。 创建常量函数的一种更快、更灵活的方法是使用可以提供任何常量值(不仅仅是零)的 lambda 函数:
constant functions. A faster and more flexible way to create constant functions
 
is to use a lambda function which can supply any constant value (not just
 
zero):
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第954行: 第802行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; def constant_factory(value):
+
<syntaxhighlight lang="python">>>> def constant_factory(value):
 
...    return lambda: value
 
...    return lambda: value
&gt;&gt;&gt; d = defaultdict(constant_factory('&lt;missing&gt;'))
+
>>> d = defaultdict(constant_factory('<missing>'))
&gt;&gt;&gt; d.update(name='John', action='ran')
+
>>> d.update(name='John', action='ran')
&gt;&gt;&gt; '%(name)s %(action)s to %(object)s' % d
+
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to &lt;missing&gt;'</pre>
+
'John ran to <missing>'</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Setting the [[#collections.defaultdict.default_factory|<code>default_factory</code>]] to [[../stdtypes#set|<code>set</code>]] makes the
+
[[#collections.defaultdict.default_factory|default_factory]] 设置为 [[../stdtypes#set|set]] 使 [[#collections.defaultdict|defaultdict]] 可用于构建集合字典:
[[#collections.defaultdict|<code>defaultdict</code>]] useful for building a dictionary of sets:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第971行: 第818行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
+
<syntaxhighlight lang="python">>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
&gt;&gt;&gt; d = defaultdict(set)
+
>>> d = defaultdict(set)
&gt;&gt;&gt; for k, v in s:
+
>>> for k, v in s:
 
...    d[k].add(v)
 
...    d[k].add(v)
 
...
 
...
&gt;&gt;&gt; sorted(d.items())
+
>>> sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]</pre>
+
[('blue', {2, 4}), ('red', {1, 3})]</syntaxhighlight>
  
 
</div>
 
</div>
第988行: 第835行:
 
<div id="namedtuple-factory-function-for-tuples-with-named-fields" class="section">
 
<div id="namedtuple-factory-function-for-tuples-with-named-fields" class="section">
  
== [[#collections.namedtuple|<code>namedtuple()</code>]] Factory Function for Tuples with Named Fields ==
+
== namedtuple() 具有命名字段的元组的工厂函数 ==
  
Named tuples assign meaning to each position in a tuple and allow for more readable,
+
命名元组为元组中的每个位置分配含义,并允许更具可读性、自文档化的代码。 它们可以在使用常规元组的任何地方使用,并且它们增加了按名称而不是位置索引访问字段的能力。
self-documenting code. They can be used wherever regular tuples are used, and
 
they add the ability to access fields by name instead of position index.
 
  
 
<dl>
 
<dl>
<dt><code>collections.</code><code>namedtuple</code><span class="sig-paren">(</span>''<span class="n">typename</span>'', ''<span class="n">field_names</span>'', ''<span class="o">*</span>'', ''<span class="n">rename</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">defaults</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">module</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">namedtuple</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">typename</span></span>'', ''<span class="n"><span class="pre">field_names</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">rename</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">defaults</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">module</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns a new tuple subclass named ''typename''. The new subclass is used to
+
<dd><p>返回一个名为 ''typename'' 的新元组子类。 新的子类用于创建类似元组的对象,这些对象具有可通过属性查找访问的字段以及可索引和可迭代的。 子类的实例也有一个有用的文档字符串(带有 typename 和 field_names)和一个有用的 <code>__repr__()</code> 方法,它以 <code>name=value</code> 格式列出元组内容。</p>
create tuple-like objects that have fields accessible by attribute lookup as
+
<p>''field_names'' 是一个字符串序列,例如 <code>['x', 'y']</code>。 或者,''field_names'' 可以是单个字符串,每个字段名由空格和/或逗号分隔,例如 <code>'x y'</code> <code>'x, y'</code></p>
well as being indexable and iterable. Instances of the subclass also have a
+
<p>除了以下划线开头的名称外,任何有效的 Python 标识符都可用于字段名。 有效标识符由字母、数字和下划线组成,但不以数字或下划线开头,并且不能是 [[../keyword#module-keyword|关键字]] ,例如 ''class''''for'''']return''''global''''pass''''raise''</p>
helpful docstring (with typename and field_names) and a helpful <code>__repr__()</code>
+
<p>如果 ''rename'' 为真,无效的字段名会自动替换为位置名称。 例如,将 <code>['abc', 'def', 'ghi', 'abc']</code> 转换为 <code>['abc', '_1', 'ghi', '_3']</code>,消除关键字 <code>def</code> 和重复的字段名 <code>abc</code></p>
method which lists the tuple contents in a <code>name=value</code> format.</p>
+
<p>''defaults'' 可以是 <code>None</code> 或默认值的 [[../../glossary#term-iterable|iterable]]。 由于具有默认值的字段必须在没有默认值的任何字段之后,因此 ''defaults'' 应用于最右边的参数。 例如,如果字段名是 <code>['x', 'y', 'z']</code> 并且默认值是 <code>(1, 2)</code>,那么 <code>x</code> 将是一个必需的参数,<code>y</code> 将默认为 [ X151X] 和 <code>z</code> 将默认为 <code>2</code></p>
<p>The ''field_names'' are a sequence of strings such as <code>['x', 'y']</code>.
+
<p>如果定义了 ''module'',则命名元组的 <code>__module__</code> 属性设置为该值。</p>
Alternatively, ''field_names'' can be a single string with each fieldname
+
<p>命名元组实例没有每个实例的字典,因此它们是轻量级的,不需要比常规元组更多的内存。</p>
separated by whitespace and/or commas, for example <code>'x y'</code> or <code>'x, y'</code>.</p>
+
<p>为了支持酸洗,命名元组类应该分配给匹配 ''typename'' 的变量。</p>
<p>Any valid Python identifier may be used for a fieldname except for names
 
starting with an underscore. Valid identifiers consist of letters, digits,
 
and underscores but do not start with a digit or underscore and cannot be
 
a [[../keyword#module-keyword|<code>keyword</code>]] such as ''class'', ''for'', ''return'', ''global'', ''pass'',
 
or ''raise''.</p>
 
<p>If ''rename'' is true, invalid fieldnames are automatically replaced
 
with positional names. For example, <code>['abc', 'def', 'ghi', 'abc']</code> is
 
converted to <code>['abc', '_1', 'ghi', '_3']</code>, eliminating the keyword
 
<code>def</code> and the duplicate fieldname <code>abc</code>.</p>
 
<p>''defaults'' can be <code>None</code> or an [[../../glossary#term-iterable|<span class="xref std std-term">iterable</span>]] of default values.
 
Since fields with a default value must come after any fields without a
 
default, the ''defaults'' are applied to the rightmost parameters. For
 
example, if the fieldnames are <code>['x', 'y', 'z']</code> and the defaults are
 
<code>(1, 2)</code>, then <code>x</code> will be a required argument, <code>y</code> will default to
 
<code>1</code>, and <code>z</code> will default to <code>2</code>.</p>
 
<p>If ''module'' is defined, the <code>__module__</code> attribute of the named tuple is
 
set to that value.</p>
 
<p>Named tuple instances do not have per-instance dictionaries, so they are
 
lightweight and require no more memory than regular tuples.</p>
 
<p>To support pickling, the named tuple class should be assigned to a variable
 
that matches ''typename''.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.1 版更改: </span>Added support for ''rename''.</p>
+
<p><span class="versionmodified changed"> 3.1 版更改: </span> 添加了对 ''重命名'' 的支持。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>The ''verbose'' and ''rename'' parameters became
+
<p><span class="versionmodified changed"> 3.6 版更改: </span> ''verbose'' ''rename'' 参数变为 [[../../glossary#keyword-only-parameter|仅关键字参数]] </p>
[[../../glossary#keyword-only-parameter|<span class="std std-ref">keyword-only arguments</span>]].</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>Added the ''module'' parameter.</p>
+
<p><span class="versionmodified changed"> 3.6 版更改: </span> 增加了 ''模块'' 参数。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.7 版更改: </span>Removed the ''verbose'' parameter and the <code>_source</code> attribute.</p>
+
<p><span class="versionmodified changed"> 3.7 版更改: </span> 删除了 ''verbose'' 参数和 <code>_source</code> 属性。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.7 版更改: </span>Added the ''defaults'' parameter and the <code>_field_defaults</code>
+
<p><span class="versionmodified changed"> 3.7 版更改: </span> 添加 ''defaults'' 参数和 <code>_field_defaults</code> 属性。</p>
attribute.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第1,057行: 第879行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; # Basic example
+
<pre class="pycon3">&gt;&gt;&gt; # Basic example
 
&gt;&gt;&gt; Point = namedtuple('Point', ['x', 'y'])
 
&gt;&gt;&gt; Point = namedtuple('Point', ['x', 'y'])
 
&gt;&gt;&gt; p = Point(11, y=22)    # instantiate with positional or keyword arguments
 
&gt;&gt;&gt; p = Point(11, y=22)    # instantiate with positional or keyword arguments
第1,073行: 第895行:
  
 
</div>
 
</div>
Named tuples are especially useful for assigning field names to result tuples returned
+
命名元组对于将字段名称分配给 [[../csv#module-csv|csv]] [[../sqlite3#module-sqlite3|sqlite3]] 模块返回的结果元组特别有用:
by the [[../csv#module-csv|<code>csv</code>]] or [[../sqlite3#module-sqlite3|<code>sqlite3</code>]] modules:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,080行: 第901行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
+
<syntaxhighlight lang="python3">EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
  
 
import csv
 
import csv
for emp in map(EmployeeRecord._make, csv.reader(open(&quot;employees.csv&quot;, &quot;rb&quot;))):
+
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
 
     print(emp.name, emp.title)
 
     print(emp.name, emp.title)
  
第1,091行: 第912行:
 
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
 
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
 
for emp in map(EmployeeRecord._make, cursor.fetchall()):
 
for emp in map(EmployeeRecord._make, cursor.fetchall()):
     print(emp.name, emp.title)</pre>
+
     print(emp.name, emp.title)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
In addition to the methods inherited from tuples, named tuples support
+
除了从元组继承的方法之外,命名元组还支持三个附加方法和两个属性。 为防止与字段名称冲突,方法和属性名称以下划线开头。
three additional methods and two attributes. To prevent conflicts with
 
field names, the method and attribute names start with an underscore.
 
  
 
<dl>
 
<dl>
<dt>''classmethod'' <code>somenamedtuple.</code><code>_make</code><span class="sig-paren">(</span>''<span class="n">iterable</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">classmethod</span>'' <span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_make</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">iterable</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Class method that makes a new instance from an existing sequence or iterable.</p>
+
<dd><p>从现有序列或可迭代创建新实例的类方法。</p>
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; t = [11, 22]
+
<pre class="pycon3">&gt;&gt;&gt; t = [11, 22]
 
&gt;&gt;&gt; Point._make(t)
 
&gt;&gt;&gt; Point._make(t)
 
Point(x=11, y=22)</pre>
 
Point(x=11, y=22)</pre>
第1,116行: 第935行:
  
 
<dl>
 
<dl>
<dt><code>somenamedtuple.</code><code>_asdict</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_asdict</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return a new [[../stdtypes#dict|<code>dict</code>]] which maps field names to their corresponding
+
<dd><p>返回一个新的 [[../stdtypes#dict|dict]],它将字段名称映射到它们对应的值:</p>
values:</p>
 
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; p = Point(x=11, y=22)
+
<pre class="pycon3">&gt;&gt;&gt; p = Point(x=11, y=22)
 
&gt;&gt;&gt; p._asdict()
 
&gt;&gt;&gt; p._asdict()
 
{'x': 11, 'y': 22}</pre>
 
{'x': 11, 'y': 22}</pre>
第1,132行: 第950行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.1 版更改: </span>Returns an [[#collections.OrderedDict|<code>OrderedDict</code>]] instead of a regular [[../stdtypes#dict|<code>dict</code>]].</p>
+
<p><span class="versionmodified changed"> 在 3.1 版中更改:</span> 返回 [[#collections.OrderedDict|OrderedDict]] 而不是常规的 [[../stdtypes#dict|dict]]</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.8 版更改: </span>Returns a regular [[../stdtypes#dict|<code>dict</code>]] instead of an [[#collections.OrderedDict|<code>OrderedDict</code>]].
+
<p><span class="versionmodified changed"> 在 3.8 版更改:</span> 返回常规 [[../stdtypes#dict|dict]] 而不是 [[#collections.OrderedDict|OrderedDict]]。 从 Python 3.7 开始,可以保证对常规 dict 进行排序。 如果需要 [[#collections.OrderedDict|OrderedDict]] 的额外功能,建议的补救措施是将结果转换为所需的类型:<code>OrderedDict(nt._asdict())</code></p>
As of Python 3.7, regular dicts are guaranteed to be ordered. If the
 
extra features of [[#collections.OrderedDict|<code>OrderedDict</code>]] are required, the suggested
 
remediation is to cast the result to the desired type:
 
<code>OrderedDict(nt._asdict())</code>.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>somenamedtuple.</code><code>_replace</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">kwargs</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_replace</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a new instance of the named tuple replacing specified fields with new
+
<dd><p>返回命名元组的新实例,用新值替换指定字段:</p>
values:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; p = Point(x=11, y=22)
+
<syntaxhighlight lang="python3">>>> p = Point(x=11, y=22)
&gt;&gt;&gt; p._replace(x=33)
+
>>> p._replace(x=33)
 
Point(x=33, y=22)
 
Point(x=33, y=22)
  
&gt;&gt;&gt; for partnum, record in inventory.items():
+
>>> for partnum, record in inventory.items():
...    inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())</pre>
+
...    inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())</syntaxhighlight>
  
 
</div>
 
</div>
第1,165行: 第978行:
  
 
<dl>
 
<dl>
<dt><code>somenamedtuple.</code><code>_fields</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_fields</span></span></dt>
<dd><p>Tuple of strings listing the field names. Useful for introspection
+
<dd><p>列出字段名称的字符串元组。 用于内省和从现有命名元组创建新的命名元组类型。</p>
and for creating new named tuple types from existing named tuples.</p>
 
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; p._fields            # view the field names
+
<pre class="pycon3">&gt;&gt;&gt; p._fields            # view the field names
 
('x', 'y')
 
('x', 'y')
  
第1,185行: 第997行:
  
 
<dl>
 
<dl>
<dt><code>somenamedtuple.</code><code>_field_defaults</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">somenamedtuple.</span></span><span class="sig-name descname"><span class="pre">_field_defaults</span></span></dt>
<dd><p>Dictionary mapping field names to default values.</p>
+
<dd><p>将字段名称映射到默认值的字典。</p>
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
+
<pre class="pycon3">&gt;&gt;&gt; Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
 
&gt;&gt;&gt; Account._field_defaults
 
&gt;&gt;&gt; Account._field_defaults
 
{'balance': 0}
 
{'balance': 0}
第1,201行: 第1,013行:
 
</div></dd></dl>
 
</div></dd></dl>
  
To retrieve a field whose name is stored in a string, use the [[../functions#getattr|<code>getattr()</code>]]
+
要检索名称存储在字符串中的字段,请使用 [[../functions#getattr|getattr()]] 函数:
function:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第1,208行: 第1,019行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; getattr(p, 'x')
+
<syntaxhighlight lang="python">>>> getattr(p, 'x')
11</pre>
+
11</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
To convert a dictionary to a named tuple, use the double-star-operator
+
要将字典转换为命名元组,请使用双星运算符(如 [[../../tutorial/controlflow#tut-unpacking-arguments|解包参数列表]] 中所述):
(as described in [[../../tutorial/controlflow#tut-unpacking-arguments|<span class="std std-ref">Unpacking Argument Lists</span>]]):
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第1,221行: 第1,031行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; d = {'x': 11, 'y': 22}
+
<syntaxhighlight lang="python">>>> d = {'x': 11, 'y': 22}
&gt;&gt;&gt; Point(**d)
+
>>> Point(**d)
Point(x=11, y=22)</pre>
+
Point(x=11, y=22)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Since a named tuple is a regular Python class, it is easy to add or change
+
由于命名元组是一个常规的 Python 类,因此很容易使用子类添加或更改功能。 以下是添加计算字段和固定宽度打印格式的方法:
functionality with a subclass. Here is how to add a calculated field and
 
a fixed-width print format:
 
  
 
<div class="highlight-pycon3 notranslate">
 
<div class="highlight-pycon3 notranslate">
第1,236行: 第1,044行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; class Point(namedtuple('Point', ['x', 'y'])):
+
<pre class="pycon3">&gt;&gt;&gt; class Point(namedtuple('Point', ['x', 'y'])):
 
...    __slots__ = ()
 
...    __slots__ = ()
 
...    @property
 
...    @property
第1,252行: 第1,060行:
  
 
</div>
 
</div>
The subclass shown above sets <code>__slots__</code> to an empty tuple. This helps
+
上面显示的子类将 <code>__slots__</code> 设置为一个空元组。 这有助于通过防止创建实例字典来保持较低的内存要求。
keep memory requirements low by preventing the creation of instance dictionaries.
 
  
Subclassing is not useful for adding new, stored fields. Instead, simply
+
子类化对于添加新的存储字段没有用处。 相反,只需从 [[#collections.somenamedtuple._fields|_fields]] 属性创建一个新的命名元组类型:
create a new named tuple type from the [[#collections.somenamedtuple._fields|<code>_fields</code>]] attribute:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第1,262行: 第1,068行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Point3D = namedtuple('Point3D', Point._fields + ('z',))</pre>
+
<syntaxhighlight lang="python">>>> Point3D = namedtuple('Point3D', Point._fields + ('z',))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Docstrings can be customized by making direct assignments to the <code>__doc__</code>
+
可以通过直接分配给 <code>__doc__</code> 字段来自定义文档字符串:
fields:
 
  
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
第1,274行: 第1,079行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; Book = namedtuple('Book', ['id', 'title', 'authors'])
+
<syntaxhighlight lang="python">>>> Book = namedtuple('Book', ['id', 'title', 'authors'])
&gt;&gt;&gt; Book.__doc__ += ': Hardcover book in active collection'
+
>>> Book.__doc__ += ': Hardcover book in active collection'
&gt;&gt;&gt; Book.id.__doc__ = '13-digit ISBN'
+
>>> Book.id.__doc__ = '13-digit ISBN'
&gt;&gt;&gt; Book.title.__doc__ = 'Title of first printing'
+
>>> Book.title.__doc__ = 'Title of first printing'
&gt;&gt;&gt; Book.authors.__doc__ = 'List of authors sorted by last name'</pre>
+
>>> Book.authors.__doc__ = 'List of authors sorted by last name'</syntaxhighlight>
  
 
</div>
 
</div>
第1,285行: 第1,090行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<span class="versionmodified changed">3.5 版更改: </span>Property docstrings became writeable.
+
<span class="versionmodified changed"> 3.5 版更改:</span> 属性文档字符串变为可写。
  
  
第1,291行: 第1,096行:
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
 
<ul>
 
<ul>
<li><p>See [[../typing#typing|<code>typing.NamedTuple</code>]] for a way to add type hints for named
+
<li><p>有关为命名元组添加类型提示的方法,请参阅 [[../typing#typing|typing.NamedTuple]]。 它还使用 [[../../reference/compound_stmts#class|class]] 关键字提供了一种优雅的表示法:</p>
tuples. It also provides an elegant notation using the [[../../reference/compound_stmts#class|<code>class</code>]]
 
keyword:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class Component(NamedTuple):
+
<syntaxhighlight lang="python3">class Component(NamedTuple):
 
     part_number: int
 
     part_number: int
 
     weight: float
 
     weight: float
     description: Optional[str] = None</pre>
+
     description: Optional[str] = None</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p>See [[../types#types|<code>types.SimpleNamespace()</code>]] for a mutable namespace based on an
+
<li><p>有关基于底层字典而不是元组的可变命名空间,请参阅 [[../types#types|types.SimpleNamespace()]]</p></li>
underlying dictionary instead of a tuple.</p></li>
+
<li><p>[[../dataclasses#module-dataclasses|dataclasses]] 模块提供了一个装饰器和函数,用于将生成的特殊方法自动添加到用户定义的类中。</p></li></ul>
<li><p>The [[../dataclasses#module-dataclasses|<code>dataclasses</code>]] module provides a decorator and functions for
 
automatically adding generated special methods to user-defined classes.</p></li></ul>
 
  
  
第1,320行: 第1,121行:
 
<div id="ordereddict-objects" class="section">
 
<div id="ordereddict-objects" class="section">
  
== [[#collections.OrderedDict|<code>OrderedDict</code>]] objects ==
+
== OrderedDict 对象 ==
  
Ordered dictionaries are just like regular dictionaries but have some extra
+
有序字典就像普通字典一样,但有一些与排序操作相关的额外功能。 由于内置的 [[../stdtypes#dict|dict]] 类获得了记住插入顺序的能力(这种新行为在 Python 3.7 中得到保证),它们变得不那么重要了。
capabilities relating to ordering operations. They have become less
 
important now that the built-in [[../stdtypes#dict|<code>dict</code>]] class gained the ability
 
to remember insertion order (this new behavior became guaranteed in
 
Python 3.7).
 
  
Some differences from [[../stdtypes#dict|<code>dict</code>]] still remain:
+
[[../stdtypes#dict|dict]] 的一些差异仍然存在:
  
* The regular [[../stdtypes#dict|<code>dict</code>]] was designed to be very good at mapping operations. Tracking insertion order was secondary.
+
* 常规的 [[../stdtypes#dict|dict]] 被设计为非常擅长映射操作。 跟踪广告订单是次要的。
* The [[#collections.OrderedDict|<code>OrderedDict</code>]] was designed to be good at reordering operations. Space efficiency, iteration speed, and the performance of update operations were secondary.
+
* [[#collections.OrderedDict|OrderedDict]] 旨在擅长重新排序操作。 空间效率、迭代速度和更新操作的性能是次要的。
* Algorithmically, [[#collections.OrderedDict|<code>OrderedDict</code>]] can handle frequent reordering operations better than [[../stdtypes#dict|<code>dict</code>]]. This makes it suitable for tracking recent accesses (for example in an [https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237 LRU cache]).
+
* 在算法上,[[#collections.OrderedDict|OrderedDict]] 可以比 [[../stdtypes#dict|dict]] 更好地处理频繁的重新排序操作。 这使它适合跟踪最近的访问(例如在 [https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237 LRU 缓存] 中)。
* The equality operation for [[#collections.OrderedDict|<code>OrderedDict</code>]] checks for matching order.
+
* [[#collections.OrderedDict|OrderedDict]] 的相等运算检查匹配顺序。
* The <code>popitem()</code> method of [[#collections.OrderedDict|<code>OrderedDict</code>]] has a different signature. It accepts an optional argument to specify which item is popped.
+
* [[#collections.OrderedDict|OrderedDict]] 的 <code>popitem()</code> 方法具有不同的签名。 它接受一个可选参数来指定弹出哪个项目。
* [[#collections.OrderedDict|<code>OrderedDict</code>]] has a <code>move_to_end()</code> method to efficiently reposition an element to an endpoint.
+
* [[#collections.OrderedDict|OrderedDict]] 有一个 <code>move_to_end()</code> 方法可以有效地将元素重新定位到端点。
* Until Python 3.8, [[../stdtypes#dict|<code>dict</code>]] lacked a <code>__reversed__()</code> method.
+
* Python 3.8 之前, [[../stdtypes#dict|dict]] 缺少 <code>__reversed__()</code> 方法。
  
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>OrderedDict</code><span class="sig-paren">(</span><span class="optional">[</span>''items''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">OrderedDict</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">items</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return an instance of a [[../stdtypes#dict|<code>dict</code>]] subclass that has methods
+
<dd><p>返回一个 [[../stdtypes#dict|dict]] 子类的实例,该子类具有专门用于重新排列字典顺序的方法。</p>
specialized for rearranging dictionary order.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.1 新版功能.</span></p>
+
<p><span class="versionmodified added">3.1 版中的新功能。</span></p>
  
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt><code>popitem</code><span class="sig-paren">(</span>''<span class="n">last</span><span class="o">=</span><span class="default_value">True</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">popitem</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">last</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>The [[#collections.OrderedDict.popitem|<code>popitem()</code>]] method for ordered dictionaries returns and removes a
+
<dd><p>有序字典的 [[#collections.OrderedDict.popitem|popitem()]] 方法返回并删除一个 (key, value) 对。 如果 ''last'' 为真,则按 LIFO 顺序返回,如果为假,则按 FIFO 顺序返回。</p></dd></dl>
(key, value) pair. The pairs are returned in
 
LIFO order if ''last'' is true
 
or FIFO order if false.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>move_to_end</code><span class="sig-paren">(</span>''<span class="n">key</span>'', ''<span class="n">last</span><span class="o">=</span><span class="default_value">True</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">move_to_end</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">key</span></span>'', ''<span class="n"><span class="pre">last</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Move an existing ''key'' to either end of an ordered dictionary. The item
+
<dd><p>将现有的 '''' 移动到有序字典的任一端。 如果 ''last'' 为真(默认值),则项目移至右端,如果 ''last'' 为假,则移至开头。 如果 ''键'' 不存在,则引发 [[../exceptions#KeyError|KeyError]]</p>
is moved to the right end if ''last'' is true (the default) or to the
 
beginning if ''last'' is false. Raises [[../exceptions#KeyError|<code>KeyError</code>]] if the ''key'' does
 
not exist:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; d = OrderedDict.fromkeys('abcde')
+
<syntaxhighlight lang="python3">>>> d = OrderedDict.fromkeys('abcde')
&gt;&gt;&gt; d.move_to_end('b')
+
>>> d.move_to_end('b')
&gt;&gt;&gt; ''.join(d.keys())
+
>>> ''.join(d.keys())
 
'acdeb'
 
'acdeb'
&gt;&gt;&gt; d.move_to_end('b', last=False)
+
>>> d.move_to_end('b', last=False)
&gt;&gt;&gt; ''.join(d.keys())
+
>>> ''.join(d.keys())
'bacde'</pre>
+
'bacde'</syntaxhighlight>
  
 
</div>
 
</div>
第1,377行: 第1,167行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.2 新版功能.</span></p>
+
<p><span class="versionmodified added">3.2 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
 
</dd></dl>
 
</dd></dl>
  
In addition to the usual mapping methods, ordered dictionaries also support
+
除了通常的映射方法,有序字典还支持使用 [[../functions#reversed|reversed()]] 的反向迭代。
reverse iteration using [[../functions#reversed|<code>reversed()</code>]].
 
  
Equality tests between [[#collections.OrderedDict|<code>OrderedDict</code>]] objects are order-sensitive
+
[[#collections.OrderedDict|OrderedDict]] 对象之间的相等性测试是顺序敏感的,并且实现为 <code>list(od1.items())==list(od2.items())</code>[[#collections.OrderedDict|OrderedDict]] 对象和其他 [[../collections.abc#collections.abc|Mapping]] 对象之间的相等性测试与常规字典一样对顺序不敏感。 这允许在使用常规字典的任何地方替换 [[#collections.OrderedDict|OrderedDict]] 对象。
and are implemented as <code>list(od1.items())==list(od2.items())</code>.
 
Equality tests between [[#collections.OrderedDict|<code>OrderedDict</code>]] objects and other
 
[[../collections.abc#collections.abc|<code>Mapping</code>]] objects are order-insensitive like regular
 
dictionaries. This allows [[#collections.OrderedDict|<code>OrderedDict</code>]] objects to be substituted
 
anywhere a regular dictionary is used.
 
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<span class="versionmodified changed">3.5 版更改: </span>The items, keys, and values [[../../glossary#term-dictionary-view|<span class="xref std std-term">views</span>]]
+
<span class="versionmodified changed"> 3.5 版更改: </span> [[#collections.OrderedDict|OrderedDict]] 的项目、键和值 [[../../glossary#term-dictionary-view|views]] 现在支持使用 [[../functions#reversed|reversed()]] 进行反向迭代。
of [[#collections.OrderedDict|<code>OrderedDict</code>]] now support reverse iteration using [[../functions#reversed|<code>reversed()</code>]].
 
  
  
第1,401行: 第1,184行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<span class="versionmodified changed">在 3.6 版更改: </span>With the acceptance of <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0468 '''PEP 468'''], order is retained for keyword arguments
+
<span class="versionmodified changed">在 3.6 版更改:</span>随着接受 <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0468 PEP 468],保留传递给 [[#collections.OrderedDict|OrderedDict]] 构造函数及其 [ X178X] 方法。
passed to the [[#collections.OrderedDict|<code>OrderedDict</code>]] constructor and its <code>update()</code>
 
method.
 
  
  
第1,409行: 第1,190行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<span class="versionmodified changed">3.9 版更改: </span>Added merge (<code>|</code>) and update (<code>|=</code>) operators, specified in <span id="index-3" class="target"></span>[https://www.python.org/dev/peps/pep-0584 '''PEP 584'''].
+
<span class="versionmodified changed"> 3.9 版更改: </span> 添加了合并 (<code>|</code>) 和更新 (<code>|=</code>) 运算符,在 <span id="index-3" class="target"></span>[https://www.python.org/dev/peps/pep-0584 PEP 584] 中指定。
  
  
第1,415行: 第1,196行:
 
<div id="ordereddict-examples-and-recipes" class="section">
 
<div id="ordereddict-examples-and-recipes" class="section">
  
=== [[#collections.OrderedDict|<code>OrderedDict</code>]] Examples and Recipes ===
+
=== OrderedDict 例子和食谱 ===
  
It is straightforward to create an ordered dictionary variant
+
创建一个有序的字典变体很简单,它记住键 ''last'' 插入的顺序。 如果新条目覆盖现有条目,则更改原始插入位置并移至末尾:
that remembers the order the keys were ''last'' inserted.
 
If a new entry overwrites an existing entry, the
 
original insertion position is changed and moved to the end:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,426行: 第1,204行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class LastUpdatedOrderedDict(OrderedDict):
+
<syntaxhighlight lang="python3">class LastUpdatedOrderedDict(OrderedDict):
 
     'Store items in the order the keys were last added'
 
     'Store items in the order the keys were last added'
  
 
     def __setitem__(self, key, value):
 
     def __setitem__(self, key, value):
 
         super().__setitem__(key, value)
 
         super().__setitem__(key, value)
         self.move_to_end(key)</pre>
+
         self.move_to_end(key)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
An [[#collections.OrderedDict|<code>OrderedDict</code>]] would also be useful for implementing
+
[[#collections.OrderedDict|OrderedDict]] 也可用于实现 [[../functools#functools|functools.lru_cache()]] 的变体:
variants of [[../functools#functools|<code>functools.lru_cache()</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,443行: 第1,220行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class LRU(OrderedDict):
+
<syntaxhighlight lang="python3">class LRU:
    'Limit size, evicting the least recently looked-up key when full'
 
  
     def __init__(self, maxsize=128, /, *args, **kwds):
+
     def __init__(self, func, maxsize=128):
 +
        self.func = func
 
         self.maxsize = maxsize
 
         self.maxsize = maxsize
         super().__init__(*args, **kwds)
+
         self.cache = OrderedDict()
 
 
    def __getitem__(self, key):
 
        value = super().__getitem__(key)
 
        self.move_to_end(key)
 
        return value
 
  
     def __setitem__(self, key, value):
+
     def __call__(self, *args):
         if key in self:
+
         if args in self.cache:
             self.move_to_end(key)
+
            value = self.cache[args]
         super().__setitem__(key, value)
+
             self.cache.move_to_end(args)
         if len(self) &gt; self.maxsize:
+
            return value
             oldest = next(iter(self))
+
         value = self.func(*args)
            del self[oldest]</pre>
+
         if len(self.cache) >= self.maxsize:
 +
             self.cache.popitem(False)
 +
        self.cache[args] = value
 +
        return value</syntaxhighlight>
  
 
</div>
 
</div>
第1,472行: 第1,247行:
 
<div id="userdict-objects" class="section">
 
<div id="userdict-objects" class="section">
  
== [[#collections.UserDict|<code>UserDict</code>]] objects ==
+
== UserDict 对象 ==
  
The class, [[#collections.UserDict|<code>UserDict</code>]] acts as a wrapper around dictionary objects.
+
[[#collections.UserDict|UserDict]] 充当字典对象的包装器。 对此类的需求已部分被直接从 [[../stdtypes#dict|dict]] 子类化的能力所取代; 但是,这个类更容易使用,因为底层字典可以作为属性访问。
The need for this class has been partially supplanted by the ability to
 
subclass directly from [[../stdtypes#dict|<code>dict</code>]]; however, this class can be easier
 
to work with because the underlying dictionary is accessible as an
 
attribute.
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>UserDict</code><span class="sig-paren">(</span><span class="optional">[</span>''initialdata''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">UserDict</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">initialdata</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Class that simulates a dictionary. The instance's contents are kept in a
+
<dd><p>模拟字典的类。 实例的内容保存在常规字典中,可通过 [[#collections.UserDict|UserDict]] 实例的 [[#collections.UserDict.data|data]] 属性访问。 如果提供了 ''initialdata'',则用其内容初始化 [[#collections.UserDict.data|data]]; 请注意,将不会保留对 ''initialdata'' 的引用,以便将其用于其他目的。</p>
regular dictionary, which is accessible via the [[#collections.UserDict.data|<code>data</code>]] attribute of
+
<p>除了支持映射的方法和操作外,[[#collections.UserDict|UserDict]] 实例还提供以下属性:</p>
[[#collections.UserDict|<code>UserDict</code>]] instances. If ''initialdata'' is provided, [[#collections.UserDict.data|<code>data</code>]] is
 
initialized with its contents; note that a reference to ''initialdata'' will not
 
be kept, allowing it be used for other purposes.</p>
 
<p>In addition to supporting the methods and operations of mappings,
 
[[#collections.UserDict|<code>UserDict</code>]] instances provide the following attribute:</p>
 
 
<dl>
 
<dl>
<dt><code>data</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">data</span></span></dt>
<dd><p>A real dictionary used to store the contents of the [[#collections.UserDict|<code>UserDict</code>]]
+
<dd><p>一个真正的字典,用于存储 [[#collections.UserDict|UserDict]] 类的内容。</p></dd></dl>
class.</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
第1,499行: 第1,264行:
 
<div id="userlist-objects" class="section">
 
<div id="userlist-objects" class="section">
  
== [[#collections.UserList|<code>UserList</code>]] objects ==
+
== UserList 对象 ==
  
This class acts as a wrapper around list objects. It is a useful base class
+
此类充当列表对象的包装器。 它是您自己的类似列表的类的有用基类,可以从它们继承并覆盖现有方法或添加新方法。 通过这种方式,人们可以向列表添加新的行为。
for your own list-like classes which can inherit from them and override
 
existing methods or add new ones. In this way, one can add new behaviors to
 
lists.
 
  
The need for this class has been partially supplanted by the ability to
+
对此类的需求已部分被直接从 [[../stdtypes#list|list]] 子类化的能力所取代; 但是,这个类更容易使用,因为底层列表可以作为属性访问。
subclass directly from [[../stdtypes#list|<code>list</code>]]; however, this class can be easier
 
to work with because the underlying list is accessible as an attribute.
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>UserList</code><span class="sig-paren">(</span><span class="optional">[</span>''list''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">UserList</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">list</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Class that simulates a list. The instance's contents are kept in a regular
+
<dd><p>模拟列表的类。 实例的内容保存在一个常规列表中,可以通过 [[#collections.UserList|UserList]] 实例的 [[#collections.UserList.data|data]] 属性访问该列表。 实例的内容最初设置为 ''list'' 的副本,默认为空列表 <code>[]</code>''list'' 可以是任何可迭代对象,例如真正的 Python 列表或 [[#collections.UserList|UserList]] 对象。</p>
list, which is accessible via the [[#collections.UserList.data|<code>data</code>]] attribute of [[#collections.UserList|<code>UserList</code>]]
+
<p>除了支持可变序列的方法和操作外,[[#collections.UserList|UserList]] 实例还提供以下属性:</p>
instances. The instance's contents are initially set to a copy of ''list'',
 
defaulting to the empty list <code>[]</code>. ''list'' can be any iterable, for
 
example a real Python list or a [[#collections.UserList|<code>UserList</code>]] object.</p>
 
<p>In addition to supporting the methods and operations of mutable sequences,
 
[[#collections.UserList|<code>UserList</code>]] instances provide the following attribute:</p>
 
 
<dl>
 
<dl>
<dt><code>data</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">data</span></span></dt>
<dd><p>A real [[../stdtypes#list|<code>list</code>]] object used to store the contents of the
+
<dd><p>一个真正的 [[../stdtypes#list|list]] 对象,用于存储 [[#collections.UserList|UserList]] 类的内容。</p></dd></dl>
[[#collections.UserList|<code>UserList</code>]] class.</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
'''Subclassing requirements:''' Subclasses of [[#collections.UserList|<code>UserList</code>]] are expected to
+
'''子类化要求:''' [[#collections.UserList|UserList]] 的子类应提供一个构造函数,该构造函数可以不带参数或一个参数调用。 返回新序列的列表操作尝试创建实际实现类的实例。 为此,它假设可以使用单个参数调用构造函数,该参数是用作数据源的序列对象。
offer a constructor which can be called with either no arguments or one
 
argument. List operations which return a new sequence attempt to create an
 
instance of the actual implementation class. To do so, it assumes that the
 
constructor can be called with a single parameter, which is a sequence object
 
used as a data source.
 
  
If a derived class does not wish to comply with this requirement, all of the
+
如果派生类不希望遵守此要求,则需要覆盖该类支持的所有特殊方法; 有关在这种情况下需要提供的方法的信息,请咨询来源。
special methods supported by this class will need to be overridden; please
 
consult the sources for information about the methods which need to be provided
 
in that case.
 
  
  
第1,541行: 第1,287行:
 
<div id="userstring-objects" class="section">
 
<div id="userstring-objects" class="section">
  
== [[#collections.UserString|<code>UserString</code>]] objects ==
+
== UserString 对象 ==
  
The class, [[#collections.UserString|<code>UserString</code>]] acts as a wrapper around string objects.
+
[[#collections.UserString|UserString]] 充当字符串对象的包装器。 对此类的需求已部分被直接从 [[../stdtypes#str|str]] 子类化的能力所取代; 但是,这个类更容易使用,因为底层字符串可以作为属性访问。
The need for this class has been partially supplanted by the ability to
 
subclass directly from [[../stdtypes#str|<code>str</code>]]; however, this class can be easier
 
to work with because the underlying string is accessible as an
 
attribute.
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>collections.</code><code>UserString</code><span class="sig-paren">(</span>''<span class="n">seq</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">collections.</span></span><span class="sig-name descname"><span class="pre">UserString</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">seq</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Class that simulates a string object. The instance's
+
<dd><p>模拟字符串对象的类。 实例的内容保存在一个常规字符串对象中,该对象可通过 [[#collections.UserString|UserString]] 实例的 [[#collections.UserString.data|data]] 属性访问。 实例的内容最初设置为 ''seq'' 的副本。 ''seq'' 参数可以是任何可以使用内置 [[../stdtypes#str|str()]] 函数转换为字符串的对象。</p>
content is kept in a regular string object, which is accessible via the
+
<p>[[#collections.UserString|UserString]] 实例除了支持字符串的方法和操作外,还提供以下属性:</p>
[[#collections.UserString.data|<code>data</code>]] attribute of [[#collections.UserString|<code>UserString</code>]] instances. The instance's
 
contents are initially set to a copy of ''seq''. The ''seq'' argument can
 
be any object which can be converted into a string using the built-in
 
[[../stdtypes#str|<code>str()</code>]] function.</p>
 
<p>In addition to supporting the methods and operations of strings,
 
[[#collections.UserString|<code>UserString</code>]] instances provide the following attribute:</p>
 
 
<dl>
 
<dl>
<dt><code>data</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">data</span></span></dt>
<dd><p>A real [[../stdtypes#str|<code>str</code>]] object used to store the contents of the
+
<dd><p>一个真正的 [[../stdtypes#str|str]] 对象,用于存储 [[#collections.UserString|UserString]] 类的内容。</p></dd></dl>
[[#collections.UserString|<code>UserString</code>]] class.</p></dd></dl>
 
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>New methods <code>__getnewargs__</code>, <code>__rmod__</code>, <code>casefold</code>,
+
<p><span class="versionmodified changed">3.5 版本更改:</span>新方法 <code>__getnewargs__</code><code>__rmod__</code><code>casefold</code><code>format_map</code><code>isprintable</code> 和 [ X104X]。</p>
<code>format_map</code>, <code>isprintable</code>, and <code>maketrans</code>.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第1,573行: 第1,307行:
  
 
</div>
 
</div>
 +
 +
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

collections — 容器数据类型

源代码: :source:`Lib/collections/__init__.py`



该模块实现了专门的容器数据类型,为 Python 的通用内置容器 dictlistsettuple 提供了替代方案。

namedtuple() 用于创建具有命名字段的元组子类的工厂函数
deque 类似列表的容器,两端具有快速追加和弹出
ChainMap 用于创建多个映射的单个视图的类 dict 类
Counter 用于计算可散列对象的 dict 子类
OrderedDict 添加了记住订单条目的 dict 子类
defaultdict dict 子类调用工厂函数来提供缺失值
UserDict 围绕字典对象的包装器,以便于 dict 子类化
UserList 列表对象的包装器,以便于列表子类化
UserString 围绕字符串对象的包装器,以便于字符串子类化

ChainMap 对象

3.3 版中的新功能。


提供了一个 ChainMap 类,用于快速链接多个映射,以便将它们视为一个单元。 它通常比创建新字典并运行多个 update() 调用快得多。

该类可用于模拟嵌套作用域,并可用于模板化。

class collections.ChainMap(*maps)

ChainMap 将多个字典或其他映射组合在一起以创建单个可更新视图。 如果未指定 maps,则提供单个空字典,以便新链始终具有至少一个映射。

底层映射存储在一个列表中。 该列表是公开的,可以使用 maps 属性访问或更新。 没有其他状态。

查找会连续搜索底层映射,直到找到一个键。 相比之下,写入、更新和删除仅对第一个映射进行操作。

ChainMap 通过引用合并了底层映射。 因此,如果底层映射之一得到更新,这些更改将反映在 ChainMap 中。

支持所有常用的字典方法。 此外,还有一个 maps 属性,一个用于创建新子上下文的方法,以及一个用于访问除第一个映射之外的所有映射的属性:

maps

用户可更新的映射列表。 该列表按从第一个搜索到最后一个搜索的顺序排列。 它是唯一的存储状态,可以修改以更改要搜索的映射。 该列表应始终包含至少一个映射。

new_child(m=None)

返回一个新的 ChainMap,其中包含一个新地图,后跟当前实例中的所有地图。 如果指定了 m,则它成为映射列表最前面的新映射; 如果未指定,则使用空字典,因此对 d.new_child() 的调用等效于:ChainMap({}, *d.maps)。 此方法用于创建可以在不更改任何父映射中的值的情况下更新的子上下文。

3.4 版更改: 添加了可选的 m 参数。

parents

属性返回一个新的 ChainMap,其中包含当前实例中除第一个之外的所有地图。 这对于跳过搜索中的第一个地图很有用。 用例类似于 嵌套作用域 中使用的 nonlocal 关键字的用例。 这些用例还与内置 super() 函数的用例并行。 对 d.parents 的引用相当于:ChainMap(*d.maps[1:])

注意,ChainMap() 的迭代顺序是通过扫描从后到前的映射来确定的:

>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']

这给出了与从最后一个映射开始的一系列 dict.update() 调用相同的顺序:

>>> combined = baseline.copy()
>>> combined.update(adjustments)
>>> list(combined)
['music', 'art', 'opera']

3.9 版更改: 添加了对 ||= 运算符的支持,在 PEP 584 中指定。

也可以看看


ChainMap 例子和食谱

本节展示了使用链式地图的各种方法。

模拟Python内部查找链的例子:

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 is not None}

combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])

使用 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 类只对链中的第一个映射进行更新(写入和删除),而查找将搜索整个链。 但是,如果需要深度写入和删除,很容易创建一个子类来更新链中更深层次的键:

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

计数器对象

提供了一个计数器工具来支持方便和快速的计数。 例如:

>>> # 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 是一个 dict 子类,用于计算可散列对象。 它是一个集合,其中元素存储为字典键,它们的计数存储为字典值。 计数可以是任何整数值,包括零或负计数。 Counter 类类似于其他语言中的 bag 或 multisets。

元素从 可迭代 计数或从另一个 映射 (或计数器)初始化:

>>> 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 对象有一个字典接口,除了它们为丢失的项目返回零计数而不是引发 KeyError

>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0

将计数设置为零不会从计数器中删除元素。 使用 del 将其完全删除:

>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry

3.1 版中的新功能。

3.7 版本变更: 作为 dict 子类,Counter 继承了记忆插入顺序的能力。 Counter 对象上的数学运算也保持顺序。 结果按照在左操作数中首次遇到元素的时间和在右操作数中遇到的顺序进行排序。

Counter 对象支持三种超出所有字典可用的方法:

elements()

在元素上返回一个迭代器,每个元素的重复次数与其计数相同。 元素按第一次遇到的顺序返回。 如果元素的计数小于 1,则 elements() 将忽略它。

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
most_common([n])

返回 n 最常见元素的列表及其从最常见到最少的计数。 如果省略 nNone,则 most_common() 返回计数器中的 all 元素。 具有相等计数的元素按第一次遇到的顺序排序:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
subtract([iterable-or-mapping])

可迭代 或另一个 映射 (或计数器)中减去元素。 像 dict.update() 但减去计数而不是替换它们。 输入和输出都可以为零或负。

>>> 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 对象,除了两个对计数器的工作方式不同。

fromkeys(iterable)

此类方法未为 Counter 对象实现。

update([iterable-or-mapping])

元素从 可迭代 计数或从另一个 映射 (或计数器)添加。 像 dict.update() 但增加计数而不是替换它们。 此外,iterable 应该是一个元素序列,而不是一个 (key, value) 对序列。

使用 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 对象以生成多重集(计数大于零的计数器)。 加法和减法通过增加或减去相应元素的计数来组合计数器。 交集和并集返回对应计数的最小值和最大值。 每个操作都可以接受带符号计数的输入,但输出将排除计数为零或更少的结果。

>>> 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]) 
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 类本身是一个字典子类,对其键和值没有限制。 这些值旨在是表示计数的数字,但您 可以 在值字段中存储任何内容。
  • most_common() 方法只要求值是可排序的。
  • 对于c[key] += 1等就地操作,值类型只需要支持加减。 因此分数、浮点数和小数都可以使用,并且支持负值。 update()subtract() 也是如此,它们允许输入和输出的负值和零值。
  • 多集方法仅适用于具有正值的用例。 输入可能是负数或零,但只会创建具有正值的输出。 没有类型限制,但是值类型需要支持加减比较。
  • elements() 方法需要整数计数。 它忽略零和负计数。


也可以看看

  • Smalltalk 中的包类

  • Multisets 的维基百科条目。

  • C++ multisets 教程示例。

  • 有关多重集及其用例的数学运算,请参阅克努斯,唐纳德。 计算机编程艺术第二卷,第 4.6.3 节,练习 19 .

  • 要枚举给定元素集上给定大小的所有不同多重集,请参阅 itertools.combinations_with_replacement()

    map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC


deque 对象

class collections.deque([iterable[, maxlen]])

返回一个从左到右初始化的新 deque 对象(使用 append()),数据来自 iterable。 如果未指定 iterable,则新的双端队列为空。

双端队列是栈和队列的泛化(名称发音为“deck”,是“双端队列”的缩写)。 双端队列支持线程安全、内存高效的追加和从双端队列的任一侧弹出,在任一方向上的 O(1) 性能大致相同。

尽管 list 对象支持类似的操作,但它们针对快速固定长度的操作进行了优化,并为 pop(0)insert(0, v) 操作产生 O(n) 内存移动成本,这改变了底层数据表示的大小和位置。

如果未指定 maxlenNone,则双端队列可能会增长到任意长度。 否则,双端队列受限于指定的最大长度。 一旦有界长度的双端队列已满,当添加新项目时,从另一端丢弃相应数量的项目。 有界长度的双端队列提供类似于 Unix 中的 tail 过滤器的功能。 它们还可用于跟踪仅对最近的活动感兴趣的交易和其他数据池。

Deque 对象支持以下方法:

append(x)

x 添加到双端队列的右侧。

appendleft(x)

x 添加到双端队列的左侧。

clear()

从双端队列中删除所有元素,使其长度为 0。

copy()

创建双端队列的浅拷贝。

3.5 版中的新功能。

count(x)

计算等于 x 的双端队列元素的数量。

3.2 版中的新功能。

extend(iterable)

通过附加来自可迭代参数的元素来扩展双端队列的右侧。

extendleft(iterable)

通过附加来自 iterable 的元素来扩展双端队列的左侧。 请注意,一系列左追加会导致可迭代参数中元素的顺序颠倒。

index(x[, start[, stop]])

返回 x 在双端队列中的位置(在索引 start 处或之后和索引 stop 之前)。 如果未找到,则返回第一个匹配项或引发 ValueError

3.5 版中的新功能。

insert(i, x)

x 插入双端队列中的位置 i

如果插入会导致有界双端队列增长超过 maxlen,则会引发 IndexError

3.5 版中的新功能。

pop()

从双端队列的右侧移除并返回一个元素。 如果不存在元素,则引发 IndexError

popleft()

从双端队列的左侧移除并返回一个元素。 如果不存在元素,则引发 IndexError

remove(value)

删除第一次出现的 。 如果未找到,则引发 ValueError

reverse()

原地反转双端队列的元素,然后返回 None

3.2 版中的新功能。

rotate(n=1)

向右旋转双端队列 n 步。 如果 n 为负,则向左旋转。

当双端队列不为空时,向右旋转一级相当于d.appendleft(d.pop()),向左旋转一级相当于d.append(d.popleft())

Deque 对象还提供了一个只读属性:

maxlen

双端队列的最大大小或 None 如果无界。

3.1 版中的新功能。

除上述之外,双端队列支持迭代、酸洗、len(d)reversed(d)copy.copy(d)copy.deepcopy(d)in的成员资格测试] 运算符和下标引用(例如 d[0])来访问第一个元素。 索引访问在两端都是 O(1),但在中间变慢到 O(n)。 对于快速随机访问,请改用列表。

从 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 食谱

本节展示了使用双端队列的各种方法。

有界长度的双端队列提供类似于 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

循环调度器可以用存储在deque中的输入迭代器来实现。 值是从位置零的活动迭代器产生的。 如果该迭代器耗尽,则可以使用 popleft() 将其删除; 否则,可以使用 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() 方法提供了一种实现 deque 切片和删除的方法。 例如,del d[n] 的纯 Python 实现依赖于 rotate() 方法来定位要弹出的元素:

def delete_nth(d, n):
    d.rotate(-n)
    d.popleft()
    d.rotate(n)

要实现 deque 切片,请使用类似的方法应用 rotate() 将目标元素带到双端队列的左侧。 使用 popleft() 删除旧条目,使用 extend() 添加新条目,然后反向旋转。 通过对该方法的微小改动,很容易实现 Forth 风格的堆栈操作,例如 dupdropswapover、[ X152X]、rotroll


defaultdict 对象

class collections.defaultdict(default_factory=None, /[, ...])

返回一个新的类似字典的对象。 defaultdict 是内置的 dict 类的子类。 它覆盖了一种方法并添加了一个可写的实例变量。 其余功能与 dict 类相同,此处未记录。

第一个参数提供 default_factory 属性的初始值; 默认为 None。 所有剩余的参数都被视为传递给 dict 构造函数,包括关键字参数。

defaultdict 对象除了标准的 dict 操作之外还支持以下方法:

__missing__(key)

如果 default_factory 属性为 None,则会引发 KeyError 异常,并以 key 作为参数。

如果 default_factory 不是 None,则不带参数调用它以提供给定 key 的默认值,该值被插入到 的字典中键,并返回。

如果调用 default_factory 引发异常,则此异常将保持不变地传播。

当找不到请求的key时,该方法会被dict类的__getitem__()方法调用; 无论它返回或引发什么,然后由 __getitem__() 返回或引发。

请注意,__missing__() 不是 不是 调用除 __getitem__() 之外的任何操作。 这意味着 get() 将像普通字典一样返回 None 作为默认值,而不是使用 default_factory

defaultdict 对象支持以下实例变量:

default_factory

该属性由 __missing__() 方法使用; 它从构造函数的第一个参数(如果存在)或 None(如果不存在)初始化。

3.9 版更改: 添加了合并 (|) 和更新 (|=) 运算符,在 PEP 584 中指定。

defaultdict 示例

使用 list 作为 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 函数自动创建一个条目,该函数返回一个空的 列表list.append() 操作然后将该值附加到新列表。 当再次遇到键时,查找将正常进行(返回该键的列表)并且 list.append() 操作将另一个值添加到列表中。 这种技术比使用 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 设置为 int 使 defaultdict 可用于计数(如其他语言中的包或多重集):

>>> 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 函数调用 int() 以提供默认计数为零。 增量操作然后建立每个字母的计数。

总是返回零的函数 int() 只是常量函数的一个特例。 创建常量函数的一种更快、更灵活的方法是使用可以提供任何常量值(不仅仅是零)的 lambda 函数:

>>> 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 设置为 set 使 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(typename, field_names, *, rename=False, defaults=None, module=None)

返回一个名为 typename 的新元组子类。 新的子类用于创建类似元组的对象,这些对象具有可通过属性查找访问的字段以及可索引和可迭代的。 子类的实例也有一个有用的文档字符串(带有 typename 和 field_names)和一个有用的 __repr__() 方法,它以 name=value 格式列出元组内容。

field_names 是一个字符串序列,例如 ['x', 'y']。 或者,field_names 可以是单个字符串,每个字段名由空格和/或逗号分隔,例如 'x y''x, y'

除了以下划线开头的名称外,任何有效的 Python 标识符都可用于字段名。 有效标识符由字母、数字和下划线组成,但不以数字或下划线开头,并且不能是 关键字 ,例如 classfor]returnglobalpassraise

如果 rename 为真,无效的字段名会自动替换为位置名称。 例如,将 ['abc', 'def', 'ghi', 'abc'] 转换为 ['abc', '_1', 'ghi', '_3'],消除关键字 def 和重复的字段名 abc

defaults 可以是 None 或默认值的 iterable。 由于具有默认值的字段必须在没有默认值的任何字段之后,因此 defaults 应用于最右边的参数。 例如,如果字段名是 ['x', 'y', 'z'] 并且默认值是 (1, 2),那么 x 将是一个必需的参数,y 将默认为 [ X151X] 和 z 将默认为 2

如果定义了 module,则命名元组的 __module__ 属性设置为该值。

命名元组实例没有每个实例的字典,因此它们是轻量级的,不需要比常规元组更多的内存。

为了支持酸洗,命名元组类应该分配给匹配 typename 的变量。

3.1 版更改: 添加了对 重命名 的支持。

3.6 版更改: verboserename 参数变为 仅关键字参数

3.6 版更改: 增加了 模块 参数。

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)

命名元组对于将字段名称分配给 csvsqlite3 模块返回的结果元组特别有用:

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,它将字段名称映射到它们对应的值:

>>> p = Point(x=11, y=22)
>>> p._asdict()
{'x': 11, 'y': 22}

在 3.1 版中更改: 返回 OrderedDict 而不是常规的 dict

在 3.8 版更改: 返回常规 dict 而不是 OrderedDict。 从 Python 3.7 开始,可以保证对常规 dict 进行排序。 如果需要 OrderedDict 的额外功能,建议的补救措施是将结果转换为所需的类型:OrderedDict(nt._asdict())

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() 函数:

>>> getattr(p, 'x')
11

要将字典转换为命名元组,请使用双星运算符(如 解包参数列表 中所述):

>>> 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 属性创建一个新的命名元组类型:

>>> 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 版更改: 属性文档字符串变为可写。


也可以看看

  • 有关为命名元组添加类型提示的方法,请参阅 typing.NamedTuple。 它还使用 class 关键字提供了一种优雅的表示法:

    class Component(NamedTuple):
        part_number: int
        weight: float
        description: Optional[str] = None
  • 有关基于底层字典而不是元组的可变命名空间,请参阅 types.SimpleNamespace()

  • dataclasses 模块提供了一个装饰器和函数,用于将生成的特殊方法自动添加到用户定义的类中。


OrderedDict 对象

有序字典就像普通字典一样,但有一些与排序操作相关的额外功能。 由于内置的 dict 类获得了记住插入顺序的能力(这种新行为在 Python 3.7 中得到保证),它们变得不那么重要了。

dict 的一些差异仍然存在:

  • 常规的 dict 被设计为非常擅长映射操作。 跟踪广告订单是次要的。
  • OrderedDict 旨在擅长重新排序操作。 空间效率、迭代速度和更新操作的性能是次要的。
  • 在算法上,OrderedDict 可以比 dict 更好地处理频繁的重新排序操作。 这使它适合跟踪最近的访问(例如在 LRU 缓存 中)。
  • OrderedDict 的相等运算检查匹配顺序。
  • OrderedDictpopitem() 方法具有不同的签名。 它接受一个可选参数来指定弹出哪个项目。
  • OrderedDict 有一个 move_to_end() 方法可以有效地将元素重新定位到端点。
  • 在 Python 3.8 之前, dict 缺少 __reversed__() 方法。
class collections.OrderedDict([items])

返回一个 dict 子类的实例,该子类具有专门用于重新排列字典顺序的方法。

3.1 版中的新功能。

popitem(last=True)

有序字典的 popitem() 方法返回并删除一个 (key, value) 对。 如果 last 为真,则按 LIFO 顺序返回,如果为假,则按 FIFO 顺序返回。

move_to_end(key, last=True)

将现有的 移动到有序字典的任一端。 如果 last 为真(默认值),则项目移至右端,如果 last 为假,则移至开头。 如果 不存在,则引发 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() 的反向迭代。

OrderedDict 对象之间的相等性测试是顺序敏感的,并且实现为 list(od1.items())==list(od2.items())OrderedDict 对象和其他 Mapping 对象之间的相等性测试与常规字典一样对顺序不敏感。 这允许在使用常规字典的任何地方替换 OrderedDict 对象。

3.5 版更改: OrderedDict 的项目、键和值 views 现在支持使用 reversed() 进行反向迭代。


在 3.6 版更改:随着接受 PEP 468,保留传递给 OrderedDict 构造函数及其 [ X178X] 方法。


3.9 版更改: 添加了合并 (|) 和更新 (|=) 运算符,在 PEP 584 中指定。


OrderedDict 例子和食谱

创建一个有序的字典变体很简单,它记住键 last 插入的顺序。 如果新条目覆盖现有条目,则更改原始插入位置并移至末尾:

class LastUpdatedOrderedDict(OrderedDict):
    'Store items in the order the keys were last added'

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self.move_to_end(key)

OrderedDict 也可用于实现 functools.lru_cache() 的变体:

class LRU:

    def __init__(self, func, maxsize=128):
        self.func = func
        self.maxsize = maxsize
        self.cache = OrderedDict()

    def __call__(self, *args):
        if args in self.cache:
            value = self.cache[args]
            self.cache.move_to_end(args)
            return value
        value = self.func(*args)
        if len(self.cache) >= self.maxsize:
            self.cache.popitem(False)
        self.cache[args] = value
        return value

UserDict 对象

UserDict 充当字典对象的包装器。 对此类的需求已部分被直接从 dict 子类化的能力所取代; 但是,这个类更容易使用,因为底层字典可以作为属性访问。

class collections.UserDict([initialdata])

模拟字典的类。 实例的内容保存在常规字典中,可通过 UserDict 实例的 data 属性访问。 如果提供了 initialdata,则用其内容初始化 data; 请注意,将不会保留对 initialdata 的引用,以便将其用于其他目的。

除了支持映射的方法和操作外,UserDict 实例还提供以下属性:

data

一个真正的字典,用于存储 UserDict 类的内容。


UserList 对象

此类充当列表对象的包装器。 它是您自己的类似列表的类的有用基类,可以从它们继承并覆盖现有方法或添加新方法。 通过这种方式,人们可以向列表添加新的行为。

对此类的需求已部分被直接从 list 子类化的能力所取代; 但是,这个类更容易使用,因为底层列表可以作为属性访问。

class collections.UserList([list])

模拟列表的类。 实例的内容保存在一个常规列表中,可以通过 UserList 实例的 data 属性访问该列表。 实例的内容最初设置为 list 的副本,默认为空列表 []list 可以是任何可迭代对象,例如真正的 Python 列表或 UserList 对象。

除了支持可变序列的方法和操作外,UserList 实例还提供以下属性:

data

一个真正的 list 对象,用于存储 UserList 类的内容。

子类化要求: UserList 的子类应提供一个构造函数,该构造函数可以不带参数或一个参数调用。 返回新序列的列表操作尝试创建实际实现类的实例。 为此,它假设可以使用单个参数调用构造函数,该参数是用作数据源的序列对象。

如果派生类不希望遵守此要求,则需要覆盖该类支持的所有特殊方法; 有关在这种情况下需要提供的方法的信息,请咨询来源。


UserString 对象

UserString 充当字符串对象的包装器。 对此类的需求已部分被直接从 str 子类化的能力所取代; 但是,这个类更容易使用,因为底层字符串可以作为属性访问。

class collections.UserString(seq)

模拟字符串对象的类。 实例的内容保存在一个常规字符串对象中,该对象可通过 UserString 实例的 data 属性访问。 实例的内容最初设置为 seq 的副本。 seq 参数可以是任何可以使用内置 str() 函数转换为字符串的对象。

UserString 实例除了支持字符串的方法和操作外,还提供以下属性:

data

一个真正的 str 对象,用于存储 UserString 类的内容。

3.5 版本更改:新方法 __getnewargs____rmod__casefoldformat_mapisprintable 和 [ X104X]。