1461 lines
163 KiB
HTML
1461 lines
163 KiB
HTML
|
||
<!DOCTYPE html>
|
||
|
||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<title>collections — Container datatypes — Python 3.7.4 documentation</title>
|
||
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
|
||
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
|
||
|
||
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
|
||
<script type="text/javascript" src="../_static/jquery.js"></script>
|
||
<script type="text/javascript" src="../_static/underscore.js"></script>
|
||
<script type="text/javascript" src="../_static/doctools.js"></script>
|
||
<script type="text/javascript" src="../_static/language_data.js"></script>
|
||
|
||
<script type="text/javascript" src="../_static/sidebar.js"></script>
|
||
|
||
<link rel="search" type="application/opensearchdescription+xml"
|
||
title="Search within Python 3.7.4 documentation"
|
||
href="../_static/opensearch.xml"/>
|
||
<link rel="author" title="About these documents" href="../about.html" />
|
||
<link rel="index" title="Index" href="../genindex.html" />
|
||
<link rel="search" title="Search" href="../search.html" />
|
||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||
<link rel="next" title="collections.abc — Abstract Base Classes for Containers" href="collections.abc.html" />
|
||
<link rel="prev" title="calendar — General calendar-related functions" href="calendar.html" />
|
||
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
|
||
<link rel="canonical" href="https://docs.python.org/3/library/collections.html" />
|
||
|
||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||
<script type="text/javascript" src="../_static/switchers.js"></script>
|
||
|
||
|
||
|
||
<style>
|
||
@media only screen {
|
||
table.full-width-table {
|
||
width: 100%;
|
||
}
|
||
}
|
||
</style>
|
||
|
||
|
||
</head><body>
|
||
|
||
<div class="related" role="navigation" aria-label="related navigation">
|
||
<h3>Navigation</h3>
|
||
<ul>
|
||
<li class="right" style="margin-right: 10px">
|
||
<a href="../genindex.html" title="General Index"
|
||
accesskey="I">index</a></li>
|
||
<li class="right" >
|
||
<a href="../py-modindex.html" title="Python Module Index"
|
||
>modules</a> |</li>
|
||
<li class="right" >
|
||
<a href="collections.abc.html" title="collections.abc — Abstract Base Classes for Containers"
|
||
accesskey="N">next</a> |</li>
|
||
<li class="right" >
|
||
<a href="calendar.html" title="calendar — General calendar-related functions"
|
||
accesskey="P">previous</a> |</li>
|
||
<li><img src="../_static/py.png" alt=""
|
||
style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li>
|
||
<span class="language_switcher_placeholder">en</span>
|
||
<span class="version_switcher_placeholder">3.7.4</span>
|
||
<a href="../index.html">Documentation </a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>
|
||
<li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">Data Types</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" style="display: none" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" type="text" name="q" />
|
||
<input type="submit" value="Go" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
<script type="text/javascript">$('.inline-search').show(0);</script>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
|
||
<div class="document">
|
||
<div class="documentwrapper">
|
||
<div class="bodywrapper">
|
||
<div class="body" role="main">
|
||
|
||
<div class="section" id="module-collections">
|
||
<span id="collections-container-datatypes"></span><h1><a class="reference internal" href="#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> — Container datatypes<a class="headerlink" href="#module-collections" title="Permalink to this headline">¶</a></h1>
|
||
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/collections/__init__.py">Lib/collections/__init__.py</a></p>
|
||
<hr class="docutils" />
|
||
<p>This module implements specialized container datatypes providing alternatives to
|
||
Python’s general purpose built-in containers, <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>,
|
||
<a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, and <a class="reference internal" href="stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p>
|
||
<table class="docutils align-center">
|
||
<colgroup>
|
||
<col style="width: 24%" />
|
||
<col style="width: 76%" />
|
||
</colgroup>
|
||
<tbody>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a></p></td>
|
||
<td><p>factory function for creating tuple subclasses with named fields</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a></p></td>
|
||
<td><p>list-like container with fast appends and pops on either end</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a></p></td>
|
||
<td><p>dict-like class for creating a single view of multiple mappings</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a></p></td>
|
||
<td><p>dict subclass for counting hashable objects</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a></p></td>
|
||
<td><p>dict subclass that remembers the order entries were added</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a></p></td>
|
||
<td><p>dict subclass that calls a factory function to supply missing values</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a></p></td>
|
||
<td><p>wrapper around dictionary objects for easier dict subclassing</p></td>
|
||
</tr>
|
||
<tr class="row-even"><td><p><a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a></p></td>
|
||
<td><p>wrapper around list objects for easier list subclassing</p></td>
|
||
</tr>
|
||
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a></p></td>
|
||
<td><p>wrapper around string objects for easier string subclassing</p></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.3: </span>Moved <a class="reference internal" href="collections.abc.html#collections-abstract-base-classes"><span class="std std-ref">Collections Abstract Base Classes</span></a> to the <a class="reference internal" href="collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code></a> module.
|
||
For backwards compatibility, they continue to be visible in this module through
|
||
Python 3.7. Subsequently, they will be removed entirely.</p>
|
||
</div>
|
||
<div class="section" id="chainmap-objects">
|
||
<h2><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> objects<a class="headerlink" href="#chainmap-objects" title="Permalink to this headline">¶</a></h2>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.3.</span></p>
|
||
</div>
|
||
<p>A <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> class is provided for quickly linking a number of mappings
|
||
so they can be treated as a single unit. It is often much faster than creating
|
||
a new dictionary and running multiple <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> calls.</p>
|
||
<p>The class can be used to simulate nested scopes and is useful in templating.</p>
|
||
<dl class="class">
|
||
<dt id="collections.ChainMap">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">ChainMap</code><span class="sig-paren">(</span><em>*maps</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.ChainMap" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> groups multiple dicts or other mappings together to
|
||
create a single, updateable view. If no <em>maps</em> are specified, a single empty
|
||
dictionary is provided so that a new chain always has at least one mapping.</p>
|
||
<p>The underlying mappings are stored in a list. That list is public and can
|
||
be accessed or updated using the <em>maps</em> attribute. There is no other state.</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 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> incorporates the underlying mappings by reference. So, if
|
||
one of the underlying mappings gets updated, those changes will be reflected
|
||
in <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a>.</p>
|
||
<p>All of the usual dictionary methods are supported. In addition, there is a
|
||
<em>maps</em> attribute, a method for creating new subcontexts, and a property for
|
||
accessing all but the first mapping:</p>
|
||
<dl class="attribute">
|
||
<dt id="collections.ChainMap.maps">
|
||
<code class="descname">maps</code><a class="headerlink" href="#collections.ChainMap.maps" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A user updateable list of mappings. The list is ordered from
|
||
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 class="method">
|
||
<dt id="collections.ChainMap.new_child">
|
||
<code class="descname">new_child</code><span class="sig-paren">(</span><em>m=None</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.ChainMap.new_child" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Returns a new <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> containing a new map followed by
|
||
all of the maps in the current instance. If <code class="docutils literal notranslate"><span class="pre">m</span></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 class="docutils literal notranslate"><span class="pre">d.new_child()</span></code>
|
||
is equivalent to: <code class="docutils literal notranslate"><span class="pre">ChainMap({},</span> <span class="pre">*d.maps)</span></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">
|
||
<p><span class="versionmodified changed">Changed in version 3.4: </span>The optional <code class="docutils literal notranslate"><span class="pre">m</span></code> parameter was added.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="attribute">
|
||
<dt id="collections.ChainMap.parents">
|
||
<code class="descname">parents</code><a class="headerlink" href="#collections.ChainMap.parents" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Property returning a new <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> containing all of the maps in
|
||
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
|
||
<a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> keyword used in <a class="reference internal" href="../glossary.html#term-nested-scope"><span class="xref std std-term">nested scopes</span></a>. The use cases also parallel those for the built-in
|
||
<a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> function. A reference to <code class="docutils literal notranslate"><span class="pre">d.parents</span></code> is equivalent to:
|
||
<code class="docutils literal notranslate"><span class="pre">ChainMap(*d.maps[1:])</span></code>.</p>
|
||
</dd></dl>
|
||
|
||
<p>Note, the iteration order of a <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap()</span></code></a> is determined by
|
||
scanning the mappings last to first:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">baseline</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'music'</span><span class="p">:</span> <span class="s1">'bach'</span><span class="p">,</span> <span class="s1">'art'</span><span class="p">:</span> <span class="s1">'rembrandt'</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="n">adjustments</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'art'</span><span class="p">:</span> <span class="s1">'van gogh'</span><span class="p">,</span> <span class="s1">'opera'</span><span class="p">:</span> <span class="s1">'carmen'</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">ChainMap</span><span class="p">(</span><span class="n">adjustments</span><span class="p">,</span> <span class="n">baseline</span><span class="p">))</span>
|
||
<span class="go">['music', 'art', 'opera']</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This gives the same ordering as a series of <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> calls
|
||
starting with the last mapping:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">combined</span> <span class="o">=</span> <span class="n">baseline</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
|
||
<span class="gp">>>> </span><span class="n">combined</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">adjustments</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">combined</span><span class="p">)</span>
|
||
<span class="go">['music', 'art', 'opera']</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">See also</p>
|
||
<ul class="simple">
|
||
<li><p>The <a class="reference external" href="https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py">MultiContext class</a>
|
||
in the Enthought <a class="reference external" href="https://github.com/enthought/codetools">CodeTools package</a> has options to support
|
||
writing to any mapping in the chain.</p></li>
|
||
<li><p>Django’s <a class="reference external" href="https://github.com/django/django/blob/master/django/template/context.py">Context class</a>
|
||
for templating is a read-only chain of mappings. It also features
|
||
pushing and popping of contexts similar to the
|
||
<a class="reference internal" href="#collections.ChainMap.new_child" title="collections.ChainMap.new_child"><code class="xref py py-meth docutils literal notranslate"><span class="pre">new_child()</span></code></a> method and the
|
||
<a class="reference internal" href="#collections.ChainMap.parents" title="collections.ChainMap.parents"><code class="xref py py-attr docutils literal notranslate"><span class="pre">parents</span></code></a> property.</p></li>
|
||
<li><p>The <a class="reference external" href="https://code.activestate.com/recipes/577434/">Nested Contexts recipe</a> has options to control
|
||
whether writes and other mutations apply only to the first mapping or to
|
||
any mapping in the chain.</p></li>
|
||
<li><p>A <a class="reference external" href="https://code.activestate.com/recipes/305268/">greatly simplified read-only version of Chainmap</a>.</p></li>
|
||
</ul>
|
||
</div>
|
||
<div class="section" id="chainmap-examples-and-recipes">
|
||
<h3><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> Examples and Recipes<a class="headerlink" href="#chainmap-examples-and-recipes" title="Permalink to this headline">¶</a></h3>
|
||
<p>This section shows various approaches to working with chained maps.</p>
|
||
<p>Example of simulating Python’s internal lookup chain:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">builtins</span>
|
||
<span class="n">pylookup</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">(</span><span class="nb">locals</span><span class="p">(),</span> <span class="nb">globals</span><span class="p">(),</span> <span class="nb">vars</span><span class="p">(</span><span class="n">builtins</span><span class="p">))</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Example of letting user specified command-line arguments take precedence over
|
||
environment variables which in turn take precedence over default values:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">argparse</span>
|
||
|
||
<span class="n">defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'color'</span><span class="p">:</span> <span class="s1">'red'</span><span class="p">,</span> <span class="s1">'user'</span><span class="p">:</span> <span class="s1">'guest'</span><span class="p">}</span>
|
||
|
||
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
|
||
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">'-u'</span><span class="p">,</span> <span class="s1">'--user'</span><span class="p">)</span>
|
||
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">'-c'</span><span class="p">,</span> <span class="s1">'--color'</span><span class="p">)</span>
|
||
<span class="n">namespace</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
|
||
<span class="n">command_line_args</span> <span class="o">=</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span><span class="n">v</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">vars</span><span class="p">(</span><span class="n">namespace</span><span class="p">)</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="k">if</span> <span class="n">v</span><span class="p">}</span>
|
||
|
||
<span class="n">combined</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">(</span><span class="n">command_line_args</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">,</span> <span class="n">defaults</span><span class="p">)</span>
|
||
<span class="nb">print</span><span class="p">(</span><span class="n">combined</span><span class="p">[</span><span class="s1">'color'</span><span class="p">])</span>
|
||
<span class="nb">print</span><span class="p">(</span><span class="n">combined</span><span class="p">[</span><span class="s1">'user'</span><span class="p">])</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Example patterns for using the <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> class to simulate nested
|
||
contexts:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">c</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">()</span> <span class="c1"># Create root context</span>
|
||
<span class="n">d</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">new_child</span><span class="p">()</span> <span class="c1"># Create nested child context</span>
|
||
<span class="n">e</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">new_child</span><span class="p">()</span> <span class="c1"># Child of c, independent from d</span>
|
||
<span class="n">e</span><span class="o">.</span><span class="n">maps</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># Current context dictionary -- like Python's locals()</span>
|
||
<span class="n">e</span><span class="o">.</span><span class="n">maps</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># Root context -- like Python's globals()</span>
|
||
<span class="n">e</span><span class="o">.</span><span class="n">parents</span> <span class="c1"># Enclosing context chain -- like Python's nonlocals</span>
|
||
|
||
<span class="n">d</span><span class="p">[</span><span class="s1">'x'</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># Set value in current context</span>
|
||
<span class="n">d</span><span class="p">[</span><span class="s1">'x'</span><span class="p">]</span> <span class="c1"># Get first key in the chain of contexts</span>
|
||
<span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="s1">'x'</span><span class="p">]</span> <span class="c1"># Delete from current context</span>
|
||
<span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="c1"># All nested values</span>
|
||
<span class="n">k</span> <span class="ow">in</span> <span class="n">d</span> <span class="c1"># Check all nested values</span>
|
||
<span class="nb">len</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="c1"># Number of nested values</span>
|
||
<span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="c1"># All nested items</span>
|
||
<span class="nb">dict</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="c1"># Flatten into a regular dictionary</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> class only makes updates (writes and deletions) to the
|
||
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:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DeepChainMap</span><span class="p">(</span><span class="n">ChainMap</span><span class="p">):</span>
|
||
<span class="s1">'Variant of ChainMap that allows direct updates to inner scopes'</span>
|
||
|
||
<span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
|
||
<span class="k">for</span> <span class="n">mapping</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">maps</span><span class="p">:</span>
|
||
<span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">mapping</span><span class="p">:</span>
|
||
<span class="n">mapping</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
|
||
<span class="k">return</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">maps</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
|
||
|
||
<span class="k">def</span> <span class="nf">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
|
||
<span class="k">for</span> <span class="n">mapping</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">maps</span><span class="p">:</span>
|
||
<span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">mapping</span><span class="p">:</span>
|
||
<span class="k">del</span> <span class="n">mapping</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
|
||
<span class="k">return</span>
|
||
<span class="k">raise</span> <span class="ne">KeyError</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
|
||
|
||
<span class="o">>>></span> <span class="n">d</span> <span class="o">=</span> <span class="n">DeepChainMap</span><span class="p">({</span><span class="s1">'zebra'</span><span class="p">:</span> <span class="s1">'black'</span><span class="p">},</span> <span class="p">{</span><span class="s1">'elephant'</span><span class="p">:</span> <span class="s1">'blue'</span><span class="p">},</span> <span class="p">{</span><span class="s1">'lion'</span><span class="p">:</span> <span class="s1">'yellow'</span><span class="p">})</span>
|
||
<span class="o">>>></span> <span class="n">d</span><span class="p">[</span><span class="s1">'lion'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'orange'</span> <span class="c1"># update an existing key two levels down</span>
|
||
<span class="o">>>></span> <span class="n">d</span><span class="p">[</span><span class="s1">'snake'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'red'</span> <span class="c1"># new keys get added to the topmost dict</span>
|
||
<span class="o">>>></span> <span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="s1">'elephant'</span><span class="p">]</span> <span class="c1"># remove an existing key one level down</span>
|
||
<span class="o">>>></span> <span class="n">d</span> <span class="c1"># display result</span>
|
||
<span class="n">DeepChainMap</span><span class="p">({</span><span class="s1">'zebra'</span><span class="p">:</span> <span class="s1">'black'</span><span class="p">,</span> <span class="s1">'snake'</span><span class="p">:</span> <span class="s1">'red'</span><span class="p">},</span> <span class="p">{},</span> <span class="p">{</span><span class="s1">'lion'</span><span class="p">:</span> <span class="s1">'orange'</span><span class="p">})</span>
|
||
</pre></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="counter-objects">
|
||
<h2><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects<a class="headerlink" href="#counter-objects" title="Permalink to this headline">¶</a></h2>
|
||
<p>A counter tool is provided to support convenient and rapid tallies.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="c1"># Tally occurrences of words in a list</span>
|
||
<span class="gp">>>> </span><span class="n">cnt</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">'red'</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'red'</span><span class="p">,</span> <span class="s1">'green'</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">]:</span>
|
||
<span class="gp">... </span> <span class="n">cnt</span><span class="p">[</span><span class="n">word</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
|
||
<span class="gp">>>> </span><span class="n">cnt</span>
|
||
<span class="go">Counter({'blue': 3, 'red': 2, 'green': 1})</span>
|
||
|
||
<span class="gp">>>> </span><span class="c1"># Find the ten most common words in Hamlet</span>
|
||
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">re</span>
|
||
<span class="gp">>>> </span><span class="n">words</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">'\w+'</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'hamlet.txt'</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
|
||
<span class="gp">>>> </span><span class="n">Counter</span><span class="p">(</span><span class="n">words</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
|
||
<span class="go">[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),</span>
|
||
<span class="go"> ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]</span>
|
||
</pre></div>
|
||
</div>
|
||
<dl class="class">
|
||
<dt id="collections.Counter">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Counter</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> is a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> subclass for counting hashable objects.
|
||
It is a collection where elements are stored as dictionary keys
|
||
and their counts are stored as dictionary values. Counts are allowed to be
|
||
any integer value including zero or negative counts. The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a>
|
||
class is similar to bags or multisets in other languages.</p>
|
||
<p>Elements are counted from an <em>iterable</em> or initialized from another
|
||
<em>mapping</em> (or counter):</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span> <span class="c1"># a new, empty counter</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="s1">'gallahad'</span><span class="p">)</span> <span class="c1"># a new counter from an iterable</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">({</span><span class="s1">'red'</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">'blue'</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span> <span class="c1"># a new counter from a mapping</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">cats</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">dogs</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span> <span class="c1"># a new counter from keyword args</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Counter objects have a dictionary interface except that they return a zero
|
||
count for missing items instead of raising a <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">([</span><span class="s1">'eggs'</span><span class="p">,</span> <span class="s1">'ham'</span><span class="p">])</span>
|
||
<span class="gp">>>> </span><span class="n">c</span><span class="p">[</span><span class="s1">'bacon'</span><span class="p">]</span> <span class="c1"># count of a missing element is zero</span>
|
||
<span class="go">0</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Setting a count to zero does not remove an element from a counter.
|
||
Use <code class="docutils literal notranslate"><span class="pre">del</span></code> to remove it entirely:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span><span class="p">[</span><span class="s1">'sausage'</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span> <span class="c1"># counter entry with a zero count</span>
|
||
<span class="gp">>>> </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s1">'sausage'</span><span class="p">]</span> <span class="c1"># del actually removes the entry</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.1.</span></p>
|
||
</div>
|
||
<p>Counter objects support three methods beyond those available for all
|
||
dictionaries:</p>
|
||
<dl class="method">
|
||
<dt id="collections.Counter.elements">
|
||
<code class="descname">elements</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.elements" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Return an iterator over elements repeating each as many times as its
|
||
count. Elements are returned in arbitrary order. If an element’s count
|
||
is less than one, <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a> will ignore it.</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">elements</span><span class="p">())</span>
|
||
<span class="go">['a', 'a', 'a', 'a', 'b', 'b']</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.Counter.most_common">
|
||
<code class="descname">most_common</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.most_common" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Return a list of the <em>n</em> most common elements and their counts from the
|
||
most common to the least. If <em>n</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>,
|
||
<a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code></a> returns <em>all</em> elements in the counter.
|
||
Elements with equal counts are ordered arbitrarily:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Counter</span><span class="p">(</span><span class="s1">'abracadabra'</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="c1"># doctest: +SKIP</span>
|
||
<span class="go">[('a', 5), ('r', 2), ('b', 2)]</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.Counter.subtract">
|
||
<code class="descname">subtract</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.subtract" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Elements are subtracted from an <em>iterable</em> or from another <em>mapping</em>
|
||
(or counter). Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> but subtracts counts instead
|
||
of replacing them. Both inputs and outputs may be zero or negative.</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">c</span>
|
||
<span class="go">Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<p>The usual dictionary methods are available for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects
|
||
except for two which work differently for counters.</p>
|
||
<dl class="method">
|
||
<dt id="collections.Counter.fromkeys">
|
||
<code class="descname">fromkeys</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.fromkeys" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>This class method is not implemented for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.Counter.update">
|
||
<code class="descname">update</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.update" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Elements are counted from an <em>iterable</em> or added-in from another
|
||
<em>mapping</em> (or counter). Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> but adds counts
|
||
instead of replacing them. Also, the <em>iterable</em> is expected to be a
|
||
sequence of elements, not a sequence of <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs.</p>
|
||
</dd></dl>
|
||
|
||
</dd></dl>
|
||
|
||
<p>Common patterns for working with <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">sum</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">values</span><span class="p">())</span> <span class="c1"># total of all counts</span>
|
||
<span class="n">c</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span> <span class="c1"># reset all counts</span>
|
||
<span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># list unique elements</span>
|
||
<span class="nb">set</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># convert to a set</span>
|
||
<span class="nb">dict</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># convert to a regular dictionary</span>
|
||
<span class="n">c</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="c1"># convert to a list of (elem, cnt) pairs</span>
|
||
<span class="n">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">(</span><span class="n">list_of_pairs</span><span class="p">))</span> <span class="c1"># convert from a list of (elem, cnt) pairs</span>
|
||
<span class="n">c</span><span class="o">.</span><span class="n">most_common</span><span class="p">()[:</span><span class="o">-</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># n least common elements</span>
|
||
<span class="o">+</span><span class="n">c</span> <span class="c1"># remove zero and negative counts</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Several mathematical operations are provided for combining <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a>
|
||
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.</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">+</span> <span class="n">d</span> <span class="c1"># add two counters together: c[x] + d[x]</span>
|
||
<span class="go">Counter({'a': 4, 'b': 3})</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">-</span> <span class="n">d</span> <span class="c1"># subtract (keeping only positive counts)</span>
|
||
<span class="go">Counter({'a': 2})</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">&</span> <span class="n">d</span> <span class="c1"># intersection: min(c[x], d[x]) # doctest: +SKIP</span>
|
||
<span class="go">Counter({'a': 1, 'b': 1})</span>
|
||
<span class="gp">>>> </span><span class="n">c</span> <span class="o">|</span> <span class="n">d</span> <span class="c1"># union: max(c[x], d[x])</span>
|
||
<span class="go">Counter({'a': 3, 'b': 2})</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Unary addition and subtraction are shortcuts for adding an empty counter
|
||
or subtracting from an empty counter.</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">b</span><span class="o">=-</span><span class="mi">4</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="o">+</span><span class="n">c</span>
|
||
<span class="go">Counter({'a': 2})</span>
|
||
<span class="gp">>>> </span><span class="o">-</span><span class="n">c</span>
|
||
<span class="go">Counter({'b': 4})</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.3: </span>Added support for unary plus, unary minus, and in-place multiset operations.</p>
|
||
</div>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">Note</p>
|
||
<p>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.</p>
|
||
<ul class="simple">
|
||
<li><p>The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 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 <em>could</em> store anything in the value field.</p></li>
|
||
<li><p>The <a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code></a> method requires only that the values be orderable.</p></li>
|
||
<li><p>For in-place operations such as <code class="docutils literal notranslate"><span class="pre">c[key]</span> <span class="pre">+=</span> <span class="pre">1</span></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
|
||
<a class="reference internal" href="#collections.Counter.update" title="collections.Counter.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> and <a class="reference internal" href="#collections.Counter.subtract" title="collections.Counter.subtract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subtract()</span></code></a> which allow negative and zero values
|
||
for both inputs and outputs.</p></li>
|
||
<li><p>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.</p></li>
|
||
<li><p>The <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a> method requires integer counts. It ignores zero and
|
||
negative counts.</p></li>
|
||
</ul>
|
||
</div>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">See also</p>
|
||
<ul>
|
||
<li><p><a class="reference external" href="https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html">Bag class</a>
|
||
in Smalltalk.</p></li>
|
||
<li><p>Wikipedia entry for <a class="reference external" href="https://en.wikipedia.org/wiki/Multiset">Multisets</a>.</p></li>
|
||
<li><p><a class="reference external" href="http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm">C++ multisets</a>
|
||
tutorial with examples.</p></li>
|
||
<li><p>For mathematical operations on multisets and their use cases, see
|
||
<em>Knuth, Donald. The Art of Computer Programming Volume II,
|
||
Section 4.6.3, Exercise 19</em>.</p></li>
|
||
<li><p>To enumerate all distinct multisets of a given size over a given set of
|
||
elements, see <a class="reference internal" href="itertools.html#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations_with_replacement()</span></code></a>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">map</span><span class="p">(</span><span class="n">Counter</span><span class="p">,</span> <span class="n">combinations_with_replacement</span><span class="p">(</span><span class="s1">'ABC'</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="c1"># --> AA AB AC BB BC CC</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="deque-objects">
|
||
<h2><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> objects<a class="headerlink" href="#deque-objects" title="Permalink to this headline">¶</a></h2>
|
||
<dl class="class">
|
||
<dt id="collections.deque">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">deque</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">[</span>, <em>maxlen</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Returns a new deque object initialized left-to-right (using <a class="reference internal" href="#collections.deque.append" title="collections.deque.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a>) with
|
||
data from <em>iterable</em>. If <em>iterable</em> is not specified, the new deque is empty.</p>
|
||
<p>Deques are a generalization of stacks and queues (the name is pronounced “deck”
|
||
and is short for “double-ended queue”). Deques support thread-safe, memory
|
||
efficient appends and pops from either side of the deque with approximately the
|
||
same O(1) performance in either direction.</p>
|
||
<p>Though <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> objects support similar operations, they are optimized for
|
||
fast fixed-length operations and incur O(n) memory movement costs for
|
||
<code class="docutils literal notranslate"><span class="pre">pop(0)</span></code> and <code class="docutils literal notranslate"><span class="pre">insert(0,</span> <span class="pre">v)</span></code> operations which change both the size and
|
||
position of the underlying data representation.</p>
|
||
<p>If <em>maxlen</em> is not specified or is <code class="docutils literal notranslate"><span class="pre">None</span></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 class="docutils literal notranslate"><span class="pre">tail</span></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 class="method">
|
||
<dt id="collections.deque.append">
|
||
<code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.append" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Add <em>x</em> to the right side of the deque.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.appendleft">
|
||
<code class="descname">appendleft</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.appendleft" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Add <em>x</em> to the left side of the deque.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.clear">
|
||
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.clear" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Remove all elements from the deque leaving it with length 0.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.copy">
|
||
<code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.copy" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Create a shallow copy of the deque.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.count">
|
||
<code class="descname">count</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.count" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Count the number of deque elements equal to <em>x</em>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.extend">
|
||
<code class="descname">extend</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extend" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Extend the right side of the deque by appending elements from the iterable
|
||
argument.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.extendleft">
|
||
<code class="descname">extendleft</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extendleft" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Extend the left side of the deque by appending elements from <em>iterable</em>.
|
||
Note, the series of left appends results in reversing the order of
|
||
elements in the iterable argument.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.index">
|
||
<code class="descname">index</code><span class="sig-paren">(</span><em>x</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>stop</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.index" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Return the position of <em>x</em> in the deque (at or after index <em>start</em>
|
||
and before index <em>stop</em>). Returns the first match or raises
|
||
<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if not found.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.insert">
|
||
<code class="descname">insert</code><span class="sig-paren">(</span><em>i</em>, <em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.insert" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Insert <em>x</em> into the deque at position <em>i</em>.</p>
|
||
<p>If the insertion would cause a bounded deque to grow beyond <em>maxlen</em>,
|
||
an <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> is raised.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.pop">
|
||
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.pop" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Remove and return an element from the right side of the deque. If no
|
||
elements are present, raises an <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.popleft">
|
||
<code class="descname">popleft</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.popleft" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Remove and return an element from the left side of the deque. If no
|
||
elements are present, raises an <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.remove">
|
||
<code class="descname">remove</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.remove" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Remove the first occurrence of <em>value</em>. If not found, raises a
|
||
<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.reverse">
|
||
<code class="descname">reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.reverse" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Reverse the elements of the deque in-place and then return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.deque.rotate">
|
||
<code class="descname">rotate</code><span class="sig-paren">(</span><em>n=1</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.rotate" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Rotate the deque <em>n</em> steps to the right. If <em>n</em> is negative, rotate
|
||
to the left.</p>
|
||
<p>When the deque is not empty, rotating one step to the right is equivalent
|
||
to <code class="docutils literal notranslate"><span class="pre">d.appendleft(d.pop())</span></code>, and rotating one step to the left is
|
||
equivalent to <code class="docutils literal notranslate"><span class="pre">d.append(d.popleft())</span></code>.</p>
|
||
</dd></dl>
|
||
|
||
<p>Deque objects also provide one read-only attribute:</p>
|
||
<dl class="attribute">
|
||
<dt id="collections.deque.maxlen">
|
||
<code class="descname">maxlen</code><a class="headerlink" href="#collections.deque.maxlen" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Maximum size of a deque or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unbounded.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.1.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
</dd></dl>
|
||
|
||
<p>In addition to the above, deques support iteration, pickling, <code class="docutils literal notranslate"><span class="pre">len(d)</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">reversed(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.copy(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.deepcopy(d)</span></code>, membership testing with
|
||
the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator, and subscript references such as <code class="docutils literal notranslate"><span class="pre">d[-1]</span></code>. Indexed
|
||
access is O(1) at both ends but slows to O(n) in the middle. For fast random
|
||
access, use lists instead.</p>
|
||
<p>Starting in version 3.5, deques support <code class="docutils literal notranslate"><span class="pre">__add__()</span></code>, <code class="docutils literal notranslate"><span class="pre">__mul__()</span></code>,
|
||
and <code class="docutils literal notranslate"><span class="pre">__imul__()</span></code>.</p>
|
||
<p>Example:</p>
|
||
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s1">'ghi'</span><span class="p">)</span> <span class="c1"># make a new deque with three items</span>
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">d</span><span class="p">:</span> <span class="c1"># iterate over the deque's elements</span>
|
||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">elem</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>
|
||
<span class="go">G</span>
|
||
<span class="go">H</span>
|
||
<span class="go">I</span>
|
||
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">'j'</span><span class="p">)</span> <span class="c1"># add a new entry to the right side</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s1">'f'</span><span class="p">)</span> <span class="c1"># add a new entry to the left side</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="c1"># show the representation of the deque</span>
|
||
<span class="go">deque(['f', 'g', 'h', 'i', 'j'])</span>
|
||
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span> <span class="c1"># return and remove the rightmost item</span>
|
||
<span class="go">'j'</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span> <span class="c1"># return and remove the leftmost item</span>
|
||
<span class="go">'f'</span>
|
||
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="c1"># list the contents of the deque</span>
|
||
<span class="go">['g', 'h', 'i']</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># peek at leftmost item</span>
|
||
<span class="go">'g'</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># peek at rightmost item</span>
|
||
<span class="go">'i'</span>
|
||
|
||
<span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span> <span class="c1"># list the contents of a deque in reverse</span>
|
||
<span class="go">['i', 'h', 'g']</span>
|
||
<span class="gp">>>> </span><span class="s1">'h'</span> <span class="ow">in</span> <span class="n">d</span> <span class="c1"># search the deque</span>
|
||
<span class="go">True</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s1">'jkl'</span><span class="p">)</span> <span class="c1"># add multiple elements at once</span>
|
||
<span class="gp">>>> </span><span class="n">d</span>
|
||
<span class="go">deque(['g', 'h', 'i', 'j', 'k', 'l'])</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># right rotation</span>
|
||
<span class="gp">>>> </span><span class="n">d</span>
|
||
<span class="go">deque(['l', 'g', 'h', 'i', 'j', 'k'])</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># left rotation</span>
|
||
<span class="gp">>>> </span><span class="n">d</span>
|
||
<span class="go">deque(['g', 'h', 'i', 'j', 'k', 'l'])</span>
|
||
|
||
<span class="gp">>>> </span><span class="n">deque</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span> <span class="c1"># make a new deque in reverse order</span>
|
||
<span class="go">deque(['l', 'k', 'j', 'i', 'h', 'g'])</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span> <span class="c1"># empty the deque</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span> <span class="c1"># cannot pop from an empty deque</span>
|
||
<span class="gt">Traceback (most recent call last):</span>
|
||
<span class="n">File</span> <span class="s2">"<pyshell#6>"</span><span class="p">,</span> <span class="n">line</span> <span class="mi">1</span><span class="p">,</span> <span class="ow">in</span> <span class="o">-</span><span class="n">toplevel</span><span class="o">-</span>
|
||
<span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
|
||
<span class="gr">IndexError</span>: <span class="n">pop from an empty deque</span>
|
||
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="s1">'abc'</span><span class="p">)</span> <span class="c1"># extendleft() reverses the input order</span>
|
||
<span class="gp">>>> </span><span class="n">d</span>
|
||
<span class="go">deque(['c', 'b', 'a'])</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="section" id="deque-recipes">
|
||
<h3><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> Recipes<a class="headerlink" href="#deque-recipes" title="Permalink to this headline">¶</a></h3>
|
||
<p>This section shows various approaches to working with deques.</p>
|
||
<p>Bounded length deques provide functionality similar to the <code class="docutils literal notranslate"><span class="pre">tail</span></code> filter
|
||
in Unix:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">tail</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
|
||
<span class="s1">'Return the last n lines of a file'</span>
|
||
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">deque</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Another approach to using deques is to maintain a sequence of recently
|
||
added elements by appending to the right and popping to the left:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">moving_average</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span>
|
||
<span class="c1"># moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0</span>
|
||
<span class="c1"># http://en.wikipedia.org/wiki/Moving_average</span>
|
||
<span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
|
||
<span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="n">it</span><span class="p">,</span> <span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
|
||
<span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
|
||
<span class="n">s</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
|
||
<span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
|
||
<span class="n">s</span> <span class="o">+=</span> <span class="n">elem</span> <span class="o">-</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
|
||
<span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">elem</span><span class="p">)</span>
|
||
<span class="k">yield</span> <span class="n">s</span> <span class="o">/</span> <span class="n">n</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>A <a class="reference external" href="https://en.wikipedia.org/wiki/Round-robin_scheduling">round-robin scheduler</a> can be implemented with
|
||
input iterators stored in a <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a>. Values are yielded from the active
|
||
iterator in position zero. If that iterator is exhausted, it can be removed
|
||
with <a class="reference internal" href="#collections.deque.popleft" title="collections.deque.popleft"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popleft()</span></code></a>; otherwise, it can be cycled back to the end with
|
||
the <a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code></a> method:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">roundrobin</span><span class="p">(</span><span class="o">*</span><span class="n">iterables</span><span class="p">):</span>
|
||
<span class="s2">"roundrobin('ABC', 'D', 'EF') --> A D E B F C"</span>
|
||
<span class="n">iterators</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="nb">iter</span><span class="p">,</span> <span class="n">iterables</span><span class="p">))</span>
|
||
<span class="k">while</span> <span class="n">iterators</span><span class="p">:</span>
|
||
<span class="k">try</span><span class="p">:</span>
|
||
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
|
||
<span class="k">yield</span> <span class="nb">next</span><span class="p">(</span><span class="n">iterators</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
|
||
<span class="n">iterators</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
|
||
<span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
|
||
<span class="c1"># Remove an exhausted iterator.</span>
|
||
<span class="n">iterators</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The <a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code></a> method provides a way to implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing and
|
||
deletion. For example, a pure Python implementation of <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">d[n]</span></code> relies on
|
||
the <code class="docutils literal notranslate"><span class="pre">rotate()</span></code> method to position elements to be popped:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">delete_nth</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
|
||
<span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="n">n</span><span class="p">)</span>
|
||
<span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
|
||
<span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>To implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing, use a similar approach applying
|
||
<a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code></a> to bring a target element to the left side of the deque. Remove
|
||
old entries with <a class="reference internal" href="#collections.deque.popleft" title="collections.deque.popleft"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popleft()</span></code></a>, add new entries with <a class="reference internal" href="#collections.deque.extend" title="collections.deque.extend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code></a>, and then
|
||
reverse the rotation.
|
||
With minor variations on that approach, it is easy to implement Forth style
|
||
stack manipulations such as <code class="docutils literal notranslate"><span class="pre">dup</span></code>, <code class="docutils literal notranslate"><span class="pre">drop</span></code>, <code class="docutils literal notranslate"><span class="pre">swap</span></code>, <code class="docutils literal notranslate"><span class="pre">over</span></code>, <code class="docutils literal notranslate"><span class="pre">pick</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">rot</span></code>, and <code class="docutils literal notranslate"><span class="pre">roll</span></code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="defaultdict-objects">
|
||
<h2><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects<a class="headerlink" href="#defaultdict-objects" title="Permalink to this headline">¶</a></h2>
|
||
<dl class="class">
|
||
<dt id="collections.defaultdict">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">defaultdict</code><span class="sig-paren">(</span><span class="optional">[</span><em>default_factory</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Returns a new dictionary-like object. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> is a subclass of the
|
||
built-in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class. It overrides one method and adds one writable
|
||
instance variable. The remaining functionality is the same as for the
|
||
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class and is not documented here.</p>
|
||
<p>The first argument provides the initial value for the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>
|
||
attribute; it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>. All remaining arguments are treated the same
|
||
as if they were passed to the <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> constructor, including keyword
|
||
arguments.</p>
|
||
<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following method in addition to the
|
||
standard <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> operations:</p>
|
||
<dl class="method">
|
||
<dt id="collections.defaultdict.__missing__">
|
||
<code class="descname">__missing__</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict.__missing__" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>If the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> attribute is <code class="docutils literal notranslate"><span class="pre">None</span></code>, this raises a
|
||
<a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception with the <em>key</em> as argument.</p>
|
||
<p>If <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is called without arguments
|
||
to provide a default value for the given <em>key</em>, this value is inserted in
|
||
the dictionary for the <em>key</em>, and returned.</p>
|
||
<p>If calling <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> raises an exception this exception is
|
||
propagated unchanged.</p>
|
||
<p>This method is called by the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method of the
|
||
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class when the requested key is not found; whatever it
|
||
returns or raises is then returned or raised by <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</p>
|
||
<p>Note that <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> is <em>not</em> called for any operations besides
|
||
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>. This means that <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> will, like normal
|
||
dictionaries, return <code class="docutils literal notranslate"><span class="pre">None</span></code> as a default rather than using
|
||
<a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following instance variable:</p>
|
||
<dl class="attribute">
|
||
<dt id="collections.defaultdict.default_factory">
|
||
<code class="descname">default_factory</code><a class="headerlink" href="#collections.defaultdict.default_factory" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>This attribute is used by the <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> method; it is
|
||
initialized from the first argument to the constructor, if present, or to
|
||
<code class="docutils literal notranslate"><span class="pre">None</span></code>, if absent.</p>
|
||
</dd></dl>
|
||
|
||
</dd></dl>
|
||
|
||
<div class="section" id="defaultdict-examples">
|
||
<h3><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> Examples<a class="headerlink" href="#defaultdict-examples" title="Permalink to this headline">¶</a></h3>
|
||
<p>Using <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> as the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>, it is easy to group a
|
||
sequence of key-value pairs into a dictionary of lists:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">'yellow'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">'yellow'</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
|
||
<span class="go">[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>When each key is encountered for the first time, it is not already in the
|
||
mapping; so an entry is automatically created using the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>
|
||
function which returns an empty <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></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 class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> operation adds another value to the list. This technique is
|
||
simpler and faster than an equivalent technique using <a class="reference internal" href="stdtypes.html#dict.setdefault" title="dict.setdefault"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.setdefault()</span></code></a>:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="n">d</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
|
||
<span class="go">[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Setting the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> to <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> makes the
|
||
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for counting (like a bag or multiset in other
|
||
languages):</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s1">'mississippi'</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
|
||
<span class="go">[('i', 4), ('m', 1), ('p', 2), ('s', 4)]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>When a letter is first encountered, it is missing from the mapping, so the
|
||
<a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> function calls <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> to supply a default count of
|
||
zero. The increment operation then builds up the count for each letter.</p>
|
||
<p>The function <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> which always returns zero is just a special case of
|
||
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):</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">constant_factory</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="k">return</span> <span class="k">lambda</span><span class="p">:</span> <span class="n">value</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="n">constant_factory</span><span class="p">(</span><span class="s1">'<missing>'</span><span class="p">))</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'John'</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">'ran'</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="s1">'</span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(action)s</span><span class="s1"> to </span><span class="si">%(object)s</span><span class="s1">'</span> <span class="o">%</span> <span class="n">d</span>
|
||
<span class="go">'John ran to <missing>'</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Setting the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> to <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> makes the
|
||
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for building a dictionary of sets:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'blue'</span><span class="p">,</span> <span class="mi">4</span><span class="p">)]</span>
|
||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">set</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
|
||
<span class="gp">... </span> <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
|
||
<span class="gp">...</span>
|
||
<span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
|
||
<span class="go">[('blue', {2, 4}), ('red', {1, 3})]</span>
|
||
</pre></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="namedtuple-factory-function-for-tuples-with-named-fields">
|
||
<h2><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a> Factory Function for Tuples with Named Fields<a class="headerlink" href="#namedtuple-factory-function-for-tuples-with-named-fields" title="Permalink to this headline">¶</a></h2>
|
||
<p>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.</p>
|
||
<dl class="function">
|
||
<dt id="collections.namedtuple">
|
||
<code class="descclassname">collections.</code><code class="descname">namedtuple</code><span class="sig-paren">(</span><em>typename</em>, <em>field_names</em>, <em>*</em>, <em>rename=False</em>, <em>defaults=None</em>, <em>module=None</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.namedtuple" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Returns a new tuple subclass named <em>typename</em>. The new subclass is used to
|
||
create tuple-like objects that have fields accessible by attribute lookup as
|
||
well as being indexable and iterable. Instances of the subclass also have a
|
||
helpful docstring (with typename and field_names) and a helpful <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a>
|
||
method which lists the tuple contents in a <code class="docutils literal notranslate"><span class="pre">name=value</span></code> format.</p>
|
||
<p>The <em>field_names</em> are a sequence of strings such as <code class="docutils literal notranslate"><span class="pre">['x',</span> <span class="pre">'y']</span></code>.
|
||
Alternatively, <em>field_names</em> can be a single string with each fieldname
|
||
separated by whitespace and/or commas, for example <code class="docutils literal notranslate"><span class="pre">'x</span> <span class="pre">y'</span></code> or <code class="docutils literal notranslate"><span class="pre">'x,</span> <span class="pre">y'</span></code>.</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 <a class="reference internal" href="keyword.html#module-keyword" title="keyword: Test whether a string is a keyword in Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code></a> such as <em>class</em>, <em>for</em>, <em>return</em>, <em>global</em>, <em>pass</em>,
|
||
or <em>raise</em>.</p>
|
||
<p>If <em>rename</em> is true, invalid fieldnames are automatically replaced
|
||
with positional names. For example, <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'def',</span> <span class="pre">'ghi',</span> <span class="pre">'abc']</span></code> is
|
||
converted to <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'_1',</span> <span class="pre">'ghi',</span> <span class="pre">'_3']</span></code>, eliminating the keyword
|
||
<code class="docutils literal notranslate"><span class="pre">def</span></code> and the duplicate fieldname <code class="docutils literal notranslate"><span class="pre">abc</span></code>.</p>
|
||
<p><em>defaults</em> can be <code class="docutils literal notranslate"><span class="pre">None</span></code> or an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> of default values.
|
||
Since fields with a default value must come after any fields without a
|
||
default, the <em>defaults</em> are applied to the rightmost parameters. For
|
||
example, if the fieldnames are <code class="docutils literal notranslate"><span class="pre">['x',</span> <span class="pre">'y',</span> <span class="pre">'z']</span></code> and the defaults are
|
||
<code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2)</span></code>, then <code class="docutils literal notranslate"><span class="pre">x</span></code> will be a required argument, <code class="docutils literal notranslate"><span class="pre">y</span></code> will default to
|
||
<code class="docutils literal notranslate"><span class="pre">1</span></code>, and <code class="docutils literal notranslate"><span class="pre">z</span></code> will default to <code class="docutils literal notranslate"><span class="pre">2</span></code>.</p>
|
||
<p>If <em>module</em> is defined, the <code class="docutils literal notranslate"><span class="pre">__module__</span></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>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.1: </span>Added support for <em>rename</em>.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>verbose</em> and <em>rename</em> parameters became
|
||
<a class="reference internal" href="../glossary.html#keyword-only-parameter"><span class="std std-ref">keyword-only arguments</span></a>.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.6: </span>Added the <em>module</em> parameter.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.7: </span>Remove the <em>verbose</em> parameter and the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_source</span></code> attribute.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>defaults</em> parameter and the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_field_defaults</span></code>
|
||
attribute.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="c1"># Basic example</span>
|
||
<span class="gp">>>> </span><span class="n">Point</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Point'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'x'</span><span class="p">,</span> <span class="s1">'y'</span><span class="p">])</span>
|
||
<span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span> <span class="c1"># instantiate with positional or keyword arguments</span>
|
||
<span class="gp">>>> </span><span class="n">p</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># indexable like the plain tuple (11, 22)</span>
|
||
<span class="go">33</span>
|
||
<span class="gp">>>> </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">p</span> <span class="c1"># unpack like a regular tuple</span>
|
||
<span class="gp">>>> </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span>
|
||
<span class="go">(11, 22)</span>
|
||
<span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">p</span><span class="o">.</span><span class="n">y</span> <span class="c1"># fields also accessible by name</span>
|
||
<span class="go">33</span>
|
||
<span class="gp">>>> </span><span class="n">p</span> <span class="c1"># readable __repr__ with a name=value style</span>
|
||
<span class="go">Point(x=11, y=22)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Named tuples are especially useful for assigning field names to result tuples returned
|
||
by the <a class="reference internal" href="csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> or <a class="reference internal" href="sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> modules:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">EmployeeRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'EmployeeRecord'</span><span class="p">,</span> <span class="s1">'name, age, title, department, paygrade'</span><span class="p">)</span>
|
||
|
||
<span class="kn">import</span> <span class="nn">csv</span>
|
||
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s2">"employees.csv"</span><span class="p">,</span> <span class="s2">"rb"</span><span class="p">))):</span>
|
||
<span class="nb">print</span><span class="p">(</span><span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span><span class="p">)</span>
|
||
|
||
<span class="kn">import</span> <span class="nn">sqlite3</span>
|
||
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">'/companydata'</span><span class="p">)</span>
|
||
<span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
|
||
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">'SELECT name, age, title, department, paygrade FROM employees'</span><span class="p">)</span>
|
||
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()):</span>
|
||
<span class="nb">print</span><span class="p">(</span><span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>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.</p>
|
||
<dl class="classmethod">
|
||
<dt id="collections.somenamedtuple._make">
|
||
<em class="property">classmethod </em><code class="descclassname">somenamedtuple.</code><code class="descname">_make</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._make" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Class method that makes a new instance from an existing sequence or iterable.</p>
|
||
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="p">[</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">]</span>
|
||
<span class="gp">>>> </span><span class="n">Point</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
|
||
<span class="go">Point(x=11, y=22)</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.somenamedtuple._asdict">
|
||
<code class="descclassname">somenamedtuple.</code><code class="descname">_asdict</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._asdict" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Return a new <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> which maps field names to their corresponding
|
||
values:</p>
|
||
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
|
||
<span class="go">OrderedDict([('x', 11), ('y', 22)])</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.1: </span>Returns an <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> instead of a regular <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.somenamedtuple._replace">
|
||
<code class="descclassname">somenamedtuple.</code><code class="descname">_replace</code><span class="sig-paren">(</span><em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._replace" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Return a new instance of the named tuple replacing specified fields with new
|
||
values:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">33</span><span class="p">)</span>
|
||
<span class="go">Point(x=33, y=22)</span>
|
||
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">partnum</span><span class="p">,</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">inventory</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
|
||
<span class="gp">... </span> <span class="n">inventory</span><span class="p">[</span><span class="n">partnum</span><span class="p">]</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">newprices</span><span class="p">[</span><span class="n">partnum</span><span class="p">],</span> <span class="n">timestamp</span><span class="o">=</span><span class="n">time</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="attribute">
|
||
<dt id="collections.somenamedtuple._fields">
|
||
<code class="descclassname">somenamedtuple.</code><code class="descname">_fields</code><a class="headerlink" href="#collections.somenamedtuple._fields" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Tuple of strings listing the field names. Useful for introspection
|
||
and for creating new named tuple types from existing named tuples.</p>
|
||
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">_fields</span> <span class="c1"># view the field names</span>
|
||
<span class="go">('x', 'y')</span>
|
||
|
||
<span class="gp">>>> </span><span class="n">Color</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Color'</span><span class="p">,</span> <span class="s1">'red green blue'</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">Pixel</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Pixel'</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="n">Color</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">Pixel</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
|
||
<span class="go">Pixel(x=11, y=22, red=128, green=255, blue=0)</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="attribute">
|
||
<dt id="collections.somenamedtuple._field_defaults">
|
||
<code class="descclassname">somenamedtuple.</code><code class="descname">_field_defaults</code><a class="headerlink" href="#collections.somenamedtuple._field_defaults" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Dictionary mapping field names to default values.</p>
|
||
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Account'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'type'</span><span class="p">,</span> <span class="s1">'balance'</span><span class="p">],</span> <span class="n">defaults</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
|
||
<span class="gp">>>> </span><span class="n">Account</span><span class="o">.</span><span class="n">_field_defaults</span>
|
||
<span class="go">{'balance': 0}</span>
|
||
<span class="gp">>>> </span><span class="n">Account</span><span class="p">(</span><span class="s1">'premium'</span><span class="p">)</span>
|
||
<span class="go">Account(type='premium', balance=0)</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<p>To retrieve a field whose name is stored in a string, use the <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a>
|
||
function:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">getattr</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s1">'x'</span><span class="p">)</span>
|
||
<span class="go">11</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>To convert a dictionary to a named tuple, use the <code class="docutils literal notranslate"><span class="pre">**</span></code> operator
|
||
(as described in <a class="reference internal" href="../tutorial/controlflow.html#tut-unpacking-arguments"><span class="std std-ref">Unpacking Argument Lists</span></a>):</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'x'</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">'y'</span><span class="p">:</span> <span class="mi">22</span><span class="p">}</span>
|
||
<span class="gp">>>> </span><span class="n">Point</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
|
||
<span class="go">Point(x=11, y=22)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Since a named tuple is a regular Python class, it is easy to add or change
|
||
functionality with a subclass. Here is how to add a calculated field and
|
||
a fixed-width print format:</p>
|
||
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Point'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'x'</span><span class="p">,</span> <span class="s1">'y'</span><span class="p">])):</span>
|
||
<span class="gp">... </span> <span class="vm">__slots__</span> <span class="o">=</span> <span class="p">()</span>
|
||
<span class="gp">... </span> <span class="nd">@property</span>
|
||
<span class="gp">... </span> <span class="k">def</span> <span class="nf">hypot</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span> <span class="o">**</span> <span class="mf">0.5</span>
|
||
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="k">return</span> <span class="s1">'Point: x=</span><span class="si">%6.3f</span><span class="s1"> y=</span><span class="si">%6.3f</span><span class="s1"> hypot=</span><span class="si">%6.3f</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">hypot</span><span class="p">)</span>
|
||
|
||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Point</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="n">Point</span><span class="p">(</span><span class="mi">14</span><span class="p">,</span> <span class="mi">5</span><span class="o">/</span><span class="mi">7</span><span class="p">):</span>
|
||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="p">)</span>
|
||
<span class="go">Point: x= 3.000 y= 4.000 hypot= 5.000</span>
|
||
<span class="go">Point: x=14.000 y= 0.714 hypot=14.018</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The subclass shown above sets <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> to an empty tuple. This helps
|
||
keep memory requirements low by preventing the creation of instance dictionaries.</p>
|
||
<p>Subclassing is not useful for adding new, stored fields. Instead, simply
|
||
create a new named tuple type from the <a class="reference internal" href="#collections.somenamedtuple._fields" title="collections.somenamedtuple._fields"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields</span></code></a> attribute:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Point3D</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Point3D'</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="p">(</span><span class="s1">'z'</span><span class="p">,))</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Docstrings can be customized by making direct assignments to the <code class="docutils literal notranslate"><span class="pre">__doc__</span></code>
|
||
fields:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Book</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Book'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'id'</span><span class="p">,</span> <span class="s1">'title'</span><span class="p">,</span> <span class="s1">'authors'</span><span class="p">])</span>
|
||
<span class="gp">>>> </span><span class="n">Book</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">+=</span> <span class="s1">': Hardcover book in active collection'</span>
|
||
<span class="gp">>>> </span><span class="n">Book</span><span class="o">.</span><span class="n">id</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">'13-digit ISBN'</span>
|
||
<span class="gp">>>> </span><span class="n">Book</span><span class="o">.</span><span class="n">title</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">'Title of first printing'</span>
|
||
<span class="gp">>>> </span><span class="n">Book</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">'List of authors sorted by last name'</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.5: </span>Property docstrings became writeable.</p>
|
||
</div>
|
||
<p>Default values can be implemented by using <a class="reference internal" href="#collections.somenamedtuple._replace" title="collections.somenamedtuple._replace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_replace()</span></code></a> to
|
||
customize a prototype instance:</p>
|
||
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Account'</span><span class="p">,</span> <span class="s1">'owner balance transaction_count'</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">default_account</span> <span class="o">=</span> <span class="n">Account</span><span class="p">(</span><span class="s1">'<owner name>'</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">johns_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s1">'John'</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">janes_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s1">'Jane'</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="admonition seealso">
|
||
<p class="admonition-title">See also</p>
|
||
<ul>
|
||
<li><p>See <a class="reference internal" href="typing.html#typing.NamedTuple" title="typing.NamedTuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">typing.NamedTuple</span></code></a> for a way to add type hints for named
|
||
tuples. It also provides an elegant notation using the <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a>
|
||
keyword:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Component</span><span class="p">(</span><span class="n">NamedTuple</span><span class="p">):</span>
|
||
<span class="n">part_number</span><span class="p">:</span> <span class="nb">int</span>
|
||
<span class="n">weight</span><span class="p">:</span> <span class="nb">float</span>
|
||
<span class="n">description</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li><p>See <a class="reference internal" href="types.html#types.SimpleNamespace" title="types.SimpleNamespace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">types.SimpleNamespace()</span></code></a> for a mutable namespace based on an
|
||
underlying dictionary instead of a tuple.</p></li>
|
||
<li><p>The <a class="reference internal" href="dataclasses.html#module-dataclasses" title="dataclasses: Generate special methods on user-defined classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dataclasses</span></code></a> module provides a decorator and functions for
|
||
automatically adding generated special methods to user-defined classes.</p></li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="ordereddict-objects">
|
||
<h2><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects<a class="headerlink" href="#ordereddict-objects" title="Permalink to this headline">¶</a></h2>
|
||
<p>Ordered dictionaries are just like regular dictionaries but have some extra
|
||
capabilities relating to ordering operations. They have become less
|
||
important now that the built-in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class gained the ability
|
||
to remember insertion order (this new behavior became guaranteed in
|
||
Python 3.7).</p>
|
||
<p>Some differences from <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> still remain:</p>
|
||
<ul class="simple">
|
||
<li><p>The regular <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> was designed to be very good at mapping
|
||
operations. Tracking insertion order was secondary.</p></li>
|
||
<li><p>The <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> was designed to be good at reordering operations.
|
||
Space efficiency, iteration speed, and the performance of update
|
||
operations were secondary.</p></li>
|
||
<li><p>Algorithmically, <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> can handle frequent reordering
|
||
operations better than <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>. This makes it suitable for tracking
|
||
recent accesses (for example in an <a class="reference external" href="https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237">LRU cache</a>).</p></li>
|
||
<li><p>The equality operation for <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> checks for matching order.</p></li>
|
||
<li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code> method of <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> has a different
|
||
signature. It accepts an optional argument to specify which item is popped.</p></li>
|
||
<li><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">move_to_end()</span></code> method to
|
||
efficiently reposition an element to an endpoint.</p></li>
|
||
<li><p>Until Python 3.8, <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> lacked a <a class="reference internal" href="../reference/datamodel.html#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> method.</p></li>
|
||
</ul>
|
||
<dl class="class">
|
||
<dt id="collections.OrderedDict">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">OrderedDict</code><span class="sig-paren">(</span><span class="optional">[</span><em>items</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Return an instance of a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> subclass that has methods
|
||
specialized for rearranging dictionary order.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.1.</span></p>
|
||
</div>
|
||
<dl class="method">
|
||
<dt id="collections.OrderedDict.popitem">
|
||
<code class="descname">popitem</code><span class="sig-paren">(</span><em>last=True</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict.popitem" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>The <a class="reference internal" href="#collections.OrderedDict.popitem" title="collections.OrderedDict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> method for ordered dictionaries returns and removes a
|
||
(key, value) pair. The pairs are returned in
|
||
<abbr title="last-in, first-out">LIFO</abbr> order if <em>last</em> is true
|
||
or <abbr title="first-in, first-out">FIFO</abbr> order if false.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="method">
|
||
<dt id="collections.OrderedDict.move_to_end">
|
||
<code class="descname">move_to_end</code><span class="sig-paren">(</span><em>key</em>, <em>last=True</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict.move_to_end" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Move an existing <em>key</em> to either end of an ordered dictionary. The item
|
||
is moved to the right end if <em>last</em> is true (the default) or to the
|
||
beginning if <em>last</em> is false. Raises <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if the <em>key</em> does
|
||
not exist:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">OrderedDict</span><span class="o">.</span><span class="n">fromkeys</span><span class="p">(</span><span class="s1">'abcde'</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="s1">'b'</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="s1">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
|
||
<span class="go">'acdeb'</span>
|
||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="s1">'b'</span><span class="p">,</span> <span class="n">last</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
|
||
<span class="gp">>>> </span><span class="s1">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
|
||
<span class="go">'bacde'</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
</dd></dl>
|
||
|
||
<p>In addition to the usual mapping methods, ordered dictionaries also support
|
||
reverse iteration using <a class="reference internal" href="functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>.</p>
|
||
<p>Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects are order-sensitive
|
||
and are implemented as <code class="docutils literal notranslate"><span class="pre">list(od1.items())==list(od2.items())</span></code>.
|
||
Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects and other
|
||
<a class="reference internal" href="collections.abc.html#collections.abc.Mapping" title="collections.abc.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> objects are order-insensitive like regular
|
||
dictionaries. This allows <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects to be substituted
|
||
anywhere a regular dictionary is used.</p>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.5: </span>The items, keys, and values <a class="reference internal" href="../glossary.html#term-dictionary-view"><span class="xref std std-term">views</span></a>
|
||
of <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> now support reverse iteration using <a class="reference internal" href="functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.6: </span>With the acceptance of <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0468"><strong>PEP 468</strong></a>, order is retained for keyword arguments
|
||
passed to the <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> constructor and its <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>
|
||
method.</p>
|
||
</div>
|
||
<div class="section" id="ordereddict-examples-and-recipes">
|
||
<h3><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> Examples and Recipes<a class="headerlink" href="#ordereddict-examples-and-recipes" title="Permalink to this headline">¶</a></h3>
|
||
<p>It is straightforward to create an ordered dictionary variant
|
||
that remembers the order the keys were <em>last</em> inserted.
|
||
If a new entry overwrites an existing entry, the
|
||
original insertion position is changed and moved to the end:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LastUpdatedOrderedDict</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">):</span>
|
||
<span class="s1">'Store items in the order the keys were last added'</span>
|
||
|
||
<span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
|
||
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__setitem__</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
|
||
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>An <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> would also be useful for implementing
|
||
variants of <a class="reference internal" href="functools.html#functools.lru_cache" title="functools.lru_cache"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.lru_cache()</span></code></a>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LRU</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">):</span>
|
||
<span class="s1">'Limit size, evicting the least recently looked-up key when full'</span>
|
||
|
||
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">maxsize</span><span class="o">=</span><span class="mi">128</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">maxsize</span> <span class="o">=</span> <span class="n">maxsize</span>
|
||
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
|
||
|
||
<span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
|
||
<span class="n">value</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
|
||
<span class="k">return</span> <span class="n">value</span>
|
||
|
||
<span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
|
||
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__setitem__</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
|
||
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">></span> <span class="bp">self</span><span class="o">.</span><span class="n">maxsize</span><span class="p">:</span>
|
||
<span class="n">oldest</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
|
||
<span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="n">oldest</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="userdict-objects">
|
||
<h2><a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> objects<a class="headerlink" href="#userdict-objects" title="Permalink to this headline">¶</a></h2>
|
||
<p>The class, <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> acts as a wrapper around dictionary objects.
|
||
The need for this class has been partially supplanted by the ability to
|
||
subclass directly from <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>; however, this class can be easier
|
||
to work with because the underlying dictionary is accessible as an
|
||
attribute.</p>
|
||
<dl class="class">
|
||
<dt id="collections.UserDict">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">UserDict</code><span class="sig-paren">(</span><span class="optional">[</span><em>initialdata</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.UserDict" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Class that simulates a dictionary. The instance’s contents are kept in a
|
||
regular dictionary, which is accessible via the <a class="reference internal" href="#collections.UserDict.data" title="collections.UserDict.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> attribute of
|
||
<a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> instances. If <em>initialdata</em> is provided, <a class="reference internal" href="#collections.UserDict.data" title="collections.UserDict.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> is
|
||
initialized with its contents; note that a reference to <em>initialdata</em> will not
|
||
be kept, allowing it be used for other purposes.</p>
|
||
<p>In addition to supporting the methods and operations of mappings,
|
||
<a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> instances provide the following attribute:</p>
|
||
<dl class="attribute">
|
||
<dt id="collections.UserDict.data">
|
||
<code class="descname">data</code><a class="headerlink" href="#collections.UserDict.data" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A real dictionary used to store the contents of the <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a>
|
||
class.</p>
|
||
</dd></dl>
|
||
|
||
</dd></dl>
|
||
|
||
</div>
|
||
<div class="section" id="userlist-objects">
|
||
<h2><a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> objects<a class="headerlink" href="#userlist-objects" title="Permalink to this headline">¶</a></h2>
|
||
<p>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.</p>
|
||
<p>The need for this class has been partially supplanted by the ability to
|
||
subclass directly from <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>; however, this class can be easier
|
||
to work with because the underlying list is accessible as an attribute.</p>
|
||
<dl class="class">
|
||
<dt id="collections.UserList">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">UserList</code><span class="sig-paren">(</span><span class="optional">[</span><em>list</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.UserList" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Class that simulates a list. The instance’s contents are kept in a regular
|
||
list, which is accessible via the <a class="reference internal" href="#collections.UserList.data" title="collections.UserList.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> attribute of <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a>
|
||
instances. The instance’s contents are initially set to a copy of <em>list</em>,
|
||
defaulting to the empty list <code class="docutils literal notranslate"><span class="pre">[]</span></code>. <em>list</em> can be any iterable, for
|
||
example a real Python list or a <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> object.</p>
|
||
<p>In addition to supporting the methods and operations of mutable sequences,
|
||
<a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> instances provide the following attribute:</p>
|
||
<dl class="attribute">
|
||
<dt id="collections.UserList.data">
|
||
<code class="descname">data</code><a class="headerlink" href="#collections.UserList.data" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A real <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> object used to store the contents of the
|
||
<a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> class.</p>
|
||
</dd></dl>
|
||
|
||
</dd></dl>
|
||
|
||
<p><strong>Subclassing requirements:</strong> Subclasses of <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> are expected to
|
||
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.</p>
|
||
<p>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.</p>
|
||
</div>
|
||
<div class="section" id="userstring-objects">
|
||
<h2><a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> objects<a class="headerlink" href="#userstring-objects" title="Permalink to this headline">¶</a></h2>
|
||
<p>The class, <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> acts as a wrapper around string objects.
|
||
The need for this class has been partially supplanted by the ability to
|
||
subclass directly from <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>; however, this class can be easier
|
||
to work with because the underlying string is accessible as an
|
||
attribute.</p>
|
||
<dl class="class">
|
||
<dt id="collections.UserString">
|
||
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">UserString</code><span class="sig-paren">(</span><em>seq</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.UserString" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Class that simulates a string object. The instance’s
|
||
content is kept in a regular string object, which is accessible via the
|
||
<a class="reference internal" href="#collections.UserString.data" title="collections.UserString.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> attribute of <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> instances. The instance’s
|
||
contents are initially set to a copy of <em>seq</em>. The <em>seq</em> argument can
|
||
be any object which can be converted into a string using the built-in
|
||
<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function.</p>
|
||
<p>In addition to supporting the methods and operations of strings,
|
||
<a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> instances provide the following attribute:</p>
|
||
<dl class="attribute">
|
||
<dt id="collections.UserString.data">
|
||
<code class="descname">data</code><a class="headerlink" href="#collections.UserString.data" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A real <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> object used to store the contents of the
|
||
<a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> class.</p>
|
||
</dd></dl>
|
||
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.5: </span>New methods <code class="docutils literal notranslate"><span class="pre">__getnewargs__</span></code>, <code class="docutils literal notranslate"><span class="pre">__rmod__</span></code>, <code class="docutils literal notranslate"><span class="pre">casefold</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">format_map</span></code>, <code class="docutils literal notranslate"><span class="pre">isprintable</span></code>, and <code class="docutils literal notranslate"><span class="pre">maketrans</span></code>.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
|
||
<div class="sphinxsidebarwrapper">
|
||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||
<ul>
|
||
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code> — Container datatypes</a><ul>
|
||
<li><a class="reference internal" href="#chainmap-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code> objects</a><ul>
|
||
<li><a class="reference internal" href="#chainmap-examples-and-recipes"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code> Examples and Recipes</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#counter-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code> objects</a></li>
|
||
<li><a class="reference internal" href="#deque-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> objects</a><ul>
|
||
<li><a class="reference internal" href="#deque-recipes"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> Recipes</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#defaultdict-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> objects</a><ul>
|
||
<li><a class="reference internal" href="#defaultdict-examples"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> Examples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#namedtuple-factory-function-for-tuples-with-named-fields"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code> Factory Function for Tuples with Named Fields</a></li>
|
||
<li><a class="reference internal" href="#ordereddict-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> objects</a><ul>
|
||
<li><a class="reference internal" href="#ordereddict-examples-and-recipes"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> Examples and Recipes</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#userdict-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code> objects</a></li>
|
||
<li><a class="reference internal" href="#userlist-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code> objects</a></li>
|
||
<li><a class="reference internal" href="#userstring-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code> objects</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
|
||
<h4>Previous topic</h4>
|
||
<p class="topless"><a href="calendar.html"
|
||
title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></p>
|
||
<h4>Next topic</h4>
|
||
<p class="topless"><a href="collections.abc.html"
|
||
title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code> — Abstract Base Classes for Containers</a></p>
|
||
<div role="note" aria-label="source link">
|
||
<h3>This Page</h3>
|
||
<ul class="this-page-menu">
|
||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||
<li>
|
||
<a href="https://github.com/python/cpython/blob/3.7/Doc/library/collections.rst"
|
||
rel="nofollow">Show Source
|
||
</a>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="clearer"></div>
|
||
</div>
|
||
<div class="related" role="navigation" aria-label="related navigation">
|
||
<h3>Navigation</h3>
|
||
<ul>
|
||
<li class="right" style="margin-right: 10px">
|
||
<a href="../genindex.html" title="General Index"
|
||
>index</a></li>
|
||
<li class="right" >
|
||
<a href="../py-modindex.html" title="Python Module Index"
|
||
>modules</a> |</li>
|
||
<li class="right" >
|
||
<a href="collections.abc.html" title="collections.abc — Abstract Base Classes for Containers"
|
||
>next</a> |</li>
|
||
<li class="right" >
|
||
<a href="calendar.html" title="calendar — General calendar-related functions"
|
||
>previous</a> |</li>
|
||
<li><img src="../_static/py.png" alt=""
|
||
style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li>
|
||
<span class="language_switcher_placeholder">en</span>
|
||
<span class="version_switcher_placeholder">3.7.4</span>
|
||
<a href="../index.html">Documentation </a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>
|
||
<li class="nav-item nav-item-2"><a href="datatypes.html" >Data Types</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" style="display: none" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" type="text" name="q" />
|
||
<input type="submit" value="Go" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
<script type="text/javascript">$('.inline-search').show(0);</script>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
<div class="footer">
|
||
© <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
|
||
<br />
|
||
The Python Software Foundation is a non-profit corporation.
|
||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||
<br />
|
||
Last updated on Jul 13, 2019.
|
||
<a href="../bugs.html">Found a bug</a>?
|
||
<br />
|
||
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
|
||
</div>
|
||
|
||
</body>
|
||
</html> |