Mr.Combet Webshell
Your IP :
216.73.216.136
Server IP :
103.233.58.157
Server :
Windows NT WIN-4PGF72KEHKB 10.0 build 17763 (Windows Server 2016) AMD64
Server Software :
Microsoft-IIS/10.0
PHP Version :
7.3.25
Add File :
Submit
Add Directory :
Submit
Dir :
C:
/
Program Files
/
Python312
/
Doc
/
html
/
howto
/
Edit File Name :
sorting.html
<!DOCTYPE html> <html lang="en" data-content_root="../"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" /> <meta property="og:title" content="Sorting Techniques" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://docs.python.org/3/howto/sorting.html" /> <meta property="og:site_name" content="Python documentation" /> <meta property="og:description" content="Author, Andrew Dalke and Raymond Hettinger,. Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted lis..." /> <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" /> <meta property="og:image:alt" content="Python documentation" /> <meta name="description" content="Author, Andrew Dalke and Raymond Hettinger,. Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted lis..." /> <meta property="og:image:width" content="200" /> <meta property="og:image:height" content="200" /> <meta name="theme-color" content="#3776ab" /> <title>Sorting Techniques — Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" /> <script src="../_static/documentation_options.js?v=2c828074"></script> <script src="../_static/doctools.js?v=888ff710"></script> <script src="../_static/sphinx_highlight.js?v=dc90522c"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.12.3 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="Unicode HOWTO" href="unicode.html" /> <link rel="prev" title="Socket Programming HOWTO" href="sockets.html" /> <link rel="canonical" href="https://docs.python.org/3/howto/sorting.html" /> <style> @media only screen { table.full-width-table { width: 100%; } } </style> <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css"> <link rel="shortcut icon" type="image/png" href="../_static/py.svg" /> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> <script type="text/javascript" src="../_static/search-focus.js"></script> <script type="text/javascript" src="../_static/themetoggle.js"></script> </head> <body> <div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" /> <nav class="nav-content" role="navigation"> <label for="menuToggler" class="toggler__label"> <span></span> </label> <span class="nav-items-wrapper"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Python logo"/> </a> <span class="version_switcher_placeholder"></span> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path> </svg> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" /> <input type="submit" value="Go"/> </form> </span> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select> </label> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Sorting Techniques</a><ul> <li><a class="reference internal" href="#sorting-basics">Sorting Basics</a></li> <li><a class="reference internal" href="#key-functions">Key Functions</a></li> <li><a class="reference internal" href="#operator-module-functions-and-partial-function-evaluation">Operator Module Functions and Partial Function Evaluation</a></li> <li><a class="reference internal" href="#ascending-and-descending">Ascending and Descending</a></li> <li><a class="reference internal" href="#sort-stability-and-complex-sorts">Sort Stability and Complex Sorts</a></li> <li><a class="reference internal" href="#decorate-sort-undecorate">Decorate-Sort-Undecorate</a></li> <li><a class="reference internal" href="#comparison-functions">Comparison Functions</a></li> <li><a class="reference internal" href="#odds-and-ends">Odds and Ends</a></li> <li><a class="reference internal" href="#partial-sorts">Partial Sorts</a></li> </ul> </li> </ul> </div> <div> <h4>Previous topic</h4> <p class="topless"><a href="sockets.html" title="previous chapter">Socket Programming HOWTO</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="unicode.html" title="next chapter">Unicode HOWTO</a></p> </div> <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/main/Doc/howto/sorting.rst" rel="nofollow">Show Source </a> </li> </ul> </div> </nav> </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" 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="unicode.html" title="Unicode HOWTO" accesskey="N">next</a> |</li> <li class="right" > <a href="sockets.html" title="Socket Programming HOWTO" accesskey="P">previous</a> |</li> <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.12.3 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> »</li> <li class="nav-item nav-item-this"><a href="">Sorting Techniques</a></li> <li class="right"> <div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" /> <input type="submit" value="Go" /> </form> </div> | </li> <li class="right"> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select> </label> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="sorting-techniques"> <span id="sortinghowto"></span><h1>Sorting Techniques<a class="headerlink" href="#sorting-techniques" title="Link to this heading">¶</a></h1> <dl class="field-list simple"> <dt class="field-odd">Author<span class="colon">:</span></dt> <dd class="field-odd"><p>Andrew Dalke and Raymond Hettinger</p> </dd> </dl> <p>Python lists have a built-in <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> method that modifies the list in-place. There is also a <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> built-in function that builds a new sorted list from an iterable.</p> <p>In this document, we explore the various techniques for sorting data using Python.</p> <section id="sorting-basics"> <h2>Sorting Basics<a class="headerlink" href="#sorting-basics" title="Link to this heading">¶</a></h2> <p>A simple ascending sort is very easy: just call the <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function. It returns a new sorted list:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">sorted</span><span class="p">([</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span> <span class="go">[1, 2, 3, 4, 5]</span> </pre></div> </div> <p>You can also use the <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> method. It modifies the list in-place (and returns <code class="docutils literal notranslate"><span class="pre">None</span></code> to avoid confusion). Usually it’s less convenient than <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> - but if you don’t need the original list, it’s slightly more efficient.</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">a</span> <span class="go">[1, 2, 3, 4, 5]</span> </pre></div> </div> <p>Another difference is that the <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> method is only defined for lists. In contrast, the <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function accepts any iterable.</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">sorted</span><span class="p">({</span><span class="mi">1</span><span class="p">:</span> <span class="s1">'D'</span><span class="p">,</span> <span class="mi">2</span><span class="p">:</span> <span class="s1">'B'</span><span class="p">,</span> <span class="mi">3</span><span class="p">:</span> <span class="s1">'B'</span><span class="p">,</span> <span class="mi">4</span><span class="p">:</span> <span class="s1">'E'</span><span class="p">,</span> <span class="mi">5</span><span class="p">:</span> <span class="s1">'A'</span><span class="p">})</span> <span class="go">[1, 2, 3, 4, 5]</span> </pre></div> </div> </section> <section id="key-functions"> <h2>Key Functions<a class="headerlink" href="#key-functions" title="Link to this heading">¶</a></h2> <p>Both <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> and <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> have a <em>key</em> parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.</p> <p>For example, here’s a case-insensitive string comparison:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="s2">"This is a test string from Andrew"</span><span class="o">.</span><span class="n">split</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="nb">str</span><span class="o">.</span><span class="n">casefold</span><span class="p">)</span> <span class="go">['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']</span> </pre></div> </div> <p>The value of the <em>key</em> parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.</p> <p>A common pattern is to sort complex objects using some of the object’s indices as keys. For example:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">student_tuples</span> <span class="o">=</span> <span class="p">[</span> <span class="gp">... </span> <span class="p">(</span><span class="s1">'john'</span><span class="p">,</span> <span class="s1">'A'</span><span class="p">,</span> <span class="mi">15</span><span class="p">),</span> <span class="gp">... </span> <span class="p">(</span><span class="s1">'jane'</span><span class="p">,</span> <span class="s1">'B'</span><span class="p">,</span> <span class="mi">12</span><span class="p">),</span> <span class="gp">... </span> <span class="p">(</span><span class="s1">'dave'</span><span class="p">,</span> <span class="s1">'B'</span><span class="p">,</span> <span class="mi">10</span><span class="p">),</span> <span class="gp">... </span><span class="p">]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">student</span><span class="p">:</span> <span class="n">student</span><span class="p">[</span><span class="mi">2</span><span class="p">])</span> <span class="c1"># sort by age</span> <span class="go">[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]</span> </pre></div> </div> <p>The same technique works for objects with named attributes. For example:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Student</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">grade</span><span class="p">,</span> <span class="n">age</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">grade</span> <span class="o">=</span> <span class="n">grade</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">=</span> <span class="n">age</span> <span class="gp">... </span> <span class="k">def</span> <span class="fm">__repr__</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="nb">repr</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">grade</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span><span class="p">))</span> <span class="gp">>>> </span><span class="n">student_objects</span> <span class="o">=</span> <span class="p">[</span> <span class="gp">... </span> <span class="n">Student</span><span class="p">(</span><span class="s1">'john'</span><span class="p">,</span> <span class="s1">'A'</span><span class="p">,</span> <span class="mi">15</span><span class="p">),</span> <span class="gp">... </span> <span class="n">Student</span><span class="p">(</span><span class="s1">'jane'</span><span class="p">,</span> <span class="s1">'B'</span><span class="p">,</span> <span class="mi">12</span><span class="p">),</span> <span class="gp">... </span> <span class="n">Student</span><span class="p">(</span><span class="s1">'dave'</span><span class="p">,</span> <span class="s1">'B'</span><span class="p">,</span> <span class="mi">10</span><span class="p">),</span> <span class="gp">... </span><span class="p">]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">student</span><span class="p">:</span> <span class="n">student</span><span class="o">.</span><span class="n">age</span><span class="p">)</span> <span class="c1"># sort by age</span> <span class="go">[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]</span> </pre></div> </div> <p>Objects with named attributes can be made by a regular class as shown above, or they can be instances of <a class="reference internal" href="../library/dataclasses.html#dataclasses.dataclass" title="dataclasses.dataclass"><code class="xref py py-class docutils literal notranslate"><span class="pre">dataclass</span></code></a> or a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a>.</p> </section> <section id="operator-module-functions-and-partial-function-evaluation"> <h2>Operator Module Functions and Partial Function Evaluation<a class="headerlink" href="#operator-module-functions-and-partial-function-evaluation" title="Link to this heading">¶</a></h2> <p>The <a class="reference internal" href="../glossary.html#term-key-function"><span class="xref std std-term">key function</span></a> patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module has <a class="reference internal" href="../library/operator.html#operator.itemgetter" title="operator.itemgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itemgetter()</span></code></a>, <a class="reference internal" href="../library/operator.html#operator.attrgetter" title="operator.attrgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">attrgetter()</span></code></a>, and a <a class="reference internal" href="../library/operator.html#operator.methodcaller" title="operator.methodcaller"><code class="xref py py-func docutils literal notranslate"><span class="pre">methodcaller()</span></code></a> function.</p> <p>Using those functions, the above examples become simpler and faster:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">operator</span> <span class="kn">import</span> <span class="n">itemgetter</span><span class="p">,</span> <span class="n">attrgetter</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span> <span class="go">[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">'age'</span><span class="p">))</span> <span class="go">[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]</span> </pre></div> </div> <p>The operator module functions allow multiple levels of sorting. For example, to sort by <em>grade</em> then by <em>age</em>:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">))</span> <span class="go">[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">'grade'</span><span class="p">,</span> <span class="s1">'age'</span><span class="p">))</span> <span class="go">[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]</span> </pre></div> </div> <p>The <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module provides another helpful tool for making key-functions. The <a class="reference internal" href="../library/functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code></a> function can reduce the <a class="reference external" href="https://en.wikipedia.org/wiki/Arity">arity</a> of a multi-argument function making it suitable for use as a key-function.</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">functools</span> <span class="kn">import</span> <span class="n">partial</span> <span class="gp">>>> </span><span class="kn">from</span> <span class="nn">unicodedata</span> <span class="kn">import</span> <span class="n">normalize</span> <span class="gp">>>> </span><span class="n">names</span> <span class="o">=</span> <span class="s1">'Zoë Åbjørn Núñez Élana Zeke Abe Nubia Eloise'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">names</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">partial</span><span class="p">(</span><span class="n">normalize</span><span class="p">,</span> <span class="s1">'NFD'</span><span class="p">))</span> <span class="go">['Abe', 'Åbjørn', 'Eloise', 'Élana', 'Nubia', 'Núñez', 'Zeke', 'Zoë']</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">names</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">partial</span><span class="p">(</span><span class="n">normalize</span><span class="p">,</span> <span class="s1">'NFC'</span><span class="p">))</span> <span class="go">['Abe', 'Eloise', 'Nubia', 'Núñez', 'Zeke', 'Zoë', 'Åbjørn', 'Élana']</span> </pre></div> </div> </section> <section id="ascending-and-descending"> <h2>Ascending and Descending<a class="headerlink" href="#ascending-and-descending" title="Link to this heading">¶</a></h2> <p>Both <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> and <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> accept a <em>reverse</em> parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse <em>age</em> order:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="go">[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">'age'</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="go">[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]</span> </pre></div> </div> </section> <section id="sort-stability-and-complex-sorts"> <h2>Sort Stability and Complex Sorts<a class="headerlink" href="#sort-stability-and-complex-sorts" title="Link to this heading">¶</a></h2> <p>Sorts are guaranteed to be <a class="reference external" href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable</a>. That means that when multiple records have the same key, their original order is preserved.</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">data</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">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">2</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="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">))</span> <span class="go">[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]</span> </pre></div> </div> <p>Notice how the two records for <em>blue</em> retain their original order so that <code class="docutils literal notranslate"><span class="pre">('blue',</span> <span class="pre">1)</span></code> is guaranteed to precede <code class="docutils literal notranslate"><span class="pre">('blue',</span> <span class="pre">2)</span></code>.</p> <p>This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending <em>grade</em> and then ascending <em>age</em>, do the <em>age</em> sort first and then sort again using <em>grade</em>:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">'age'</span><span class="p">))</span> <span class="c1"># sort on secondary key</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">'grade'</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="c1"># now sort on primary key, descending</span> <span class="go">[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]</span> </pre></div> </div> <p>This can be abstracted out into a wrapper function that can take a list and tuples of field and order to sort them on multiple passes.</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">multisort</span><span class="p">(</span><span class="n">xs</span><span class="p">,</span> <span class="n">specs</span><span class="p">):</span> <span class="gp">... </span> <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">reverse</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="n">specs</span><span class="p">):</span> <span class="gp">... </span> <span class="n">xs</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="n">key</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="n">reverse</span><span class="p">)</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">xs</span> <span class="gp">>>> </span><span class="n">multisort</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">student_objects</span><span class="p">),</span> <span class="p">((</span><span class="s1">'grade'</span><span class="p">,</span> <span class="kc">True</span><span class="p">),</span> <span class="p">(</span><span class="s1">'age'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)))</span> <span class="go">[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]</span> </pre></div> </div> <p>The <a class="reference external" href="https://en.wikipedia.org/wiki/Timsort">Timsort</a> algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.</p> </section> <section id="decorate-sort-undecorate"> <h2>Decorate-Sort-Undecorate<a class="headerlink" href="#decorate-sort-undecorate" title="Link to this heading">¶</a></h2> <p>This idiom is called Decorate-Sort-Undecorate after its three steps:</p> <ul class="simple"> <li><p>First, the initial list is decorated with new values that control the sort order.</p></li> <li><p>Second, the decorated list is sorted.</p></li> <li><p>Finally, the decorations are removed, creating a list that contains only the initial values in the new order.</p></li> </ul> <p>For example, to sort the student data by <em>grade</em> using the DSU approach:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">decorated</span> <span class="o">=</span> <span class="p">[(</span><span class="n">student</span><span class="o">.</span><span class="n">grade</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">student</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">student</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">student_objects</span><span class="p">)]</span> <span class="gp">>>> </span><span class="n">decorated</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="gp">>>> </span><span class="p">[</span><span class="n">student</span> <span class="k">for</span> <span class="n">grade</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">student</span> <span class="ow">in</span> <span class="n">decorated</span><span class="p">]</span> <span class="c1"># undecorate</span> <span class="go">[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]</span> </pre></div> </div> <p>This idiom works because tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.</p> <p>It is not strictly necessary in all cases to include the index <em>i</em> in the decorated list, but including it gives two benefits:</p> <ul class="simple"> <li><p>The sort is stable – if two items have the same key, their order will be preserved in the sorted list.</p></li> <li><p>The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items. So for example the original list could contain complex numbers which cannot be sorted directly.</p></li> </ul> <p>Another name for this idiom is <a class="reference external" href="https://en.wikipedia.org/wiki/Schwartzian_transform">Schwartzian transform</a>, after Randal L. Schwartz, who popularized it among Perl programmers.</p> <p>Now that Python sorting provides key-functions, this technique is not often needed.</p> </section> <section id="comparison-functions"> <h2>Comparison Functions<a class="headerlink" href="#comparison-functions" title="Link to this heading">¶</a></h2> <p>Unlike key functions that return an absolute value for sorting, a comparison function computes the relative ordering for two inputs.</p> <p>For example, a <a class="reference external" href="https://upload.wikimedia.org/wikipedia/commons/1/17/Balance_à_tabac_1850.JPG">balance scale</a> compares two samples giving a relative ordering: lighter, equal, or heavier. Likewise, a comparison function such as <code class="docutils literal notranslate"><span class="pre">cmp(a,</span> <span class="pre">b)</span></code> will return a negative value for less-than, zero if the inputs are equal, or a positive value for greater-than.</p> <p>It is common to encounter comparison functions when translating algorithms from other languages. Also, some libraries provide comparison functions as part of their API. For example, <a class="reference internal" href="../library/locale.html#locale.strcoll" title="locale.strcoll"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.strcoll()</span></code></a> is a comparison function.</p> <p>To accommodate those situations, Python provides <a class="reference internal" href="../library/functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><code class="xref py py-class docutils literal notranslate"><span class="pre">functools.cmp_to_key</span></code></a> to wrap the comparison function to make it usable as a key function:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">sorted</span><span class="p">(</span><span class="n">words</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">cmp_to_key</span><span class="p">(</span><span class="n">strcoll</span><span class="p">))</span> <span class="c1"># locale-aware sort order</span> </pre></div> </div> </section> <section id="odds-and-ends"> <h2>Odds and Ends<a class="headerlink" href="#odds-and-ends" title="Link to this heading">¶</a></h2> <ul> <li><p>For locale aware sorting, use <a class="reference internal" href="../library/locale.html#locale.strxfrm" title="locale.strxfrm"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.strxfrm()</span></code></a> for a key function or <a class="reference internal" href="../library/locale.html#locale.strcoll" title="locale.strcoll"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.strcoll()</span></code></a> for a comparison function. This is necessary because “alphabetical” sort orderings can vary across cultures even if the underlying alphabet is the same.</p></li> <li><p>The <em>reverse</em> parameter still maintains sort stability (so that records with equal keys retain the original order). Interestingly, that effect can be simulated without the parameter by using the builtin <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> function twice:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">data</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">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">'red'</span><span class="p">,</span> <span class="mi">2</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="gp">>>> </span><span class="n">standard_way</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">double_reversed</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">data</span><span class="p">),</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">))))</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">standard_way</span> <span class="o">==</span> <span class="n">double_reversed</span> <span class="gp">>>> </span><span class="n">standard_way</span> <span class="go">[('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]</span> </pre></div> </div> </li> <li><p>The sort routines use <code class="docutils literal notranslate"><span class="pre"><</span></code> when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a> method:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Student</span><span class="o">.</span><span class="fm">__lt__</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o"><</span> <span class="n">other</span><span class="o">.</span><span class="n">age</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">)</span> <span class="go">[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]</span> </pre></div> </div> <p>However, note that <code class="docutils literal notranslate"><span class="pre"><</span></code> can fall back to using <a class="reference internal" href="../reference/datamodel.html#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a> if <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a> is not implemented (see <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-func docutils literal notranslate"><span class="pre">object.__lt__()</span></code></a> for details on the mechanics). To avoid surprises, <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0008/"><strong>PEP 8</strong></a> recommends that all six comparison methods be implemented. The <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">total_ordering()</span></code></a> decorator is provided to make that task easier.</p> </li> <li><p>Key functions need not depend directly on the objects being sorted. A key function can also access external resources. For instance, if the student grades are stored in a dictionary, they can be used to sort a separate list of student names:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">students</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'dave'</span><span class="p">,</span> <span class="s1">'john'</span><span class="p">,</span> <span class="s1">'jane'</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">newgrades</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'john'</span><span class="p">:</span> <span class="s1">'F'</span><span class="p">,</span> <span class="s1">'jane'</span><span class="p">:</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'dave'</span><span class="p">:</span> <span class="s1">'C'</span><span class="p">}</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">students</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">newgrades</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">)</span> <span class="go">['jane', 'dave', 'john']</span> </pre></div> </div> </li> </ul> </section> <section id="partial-sorts"> <h2>Partial Sorts<a class="headerlink" href="#partial-sorts" title="Link to this heading">¶</a></h2> <p>Some applications require only some of the data to be ordered. The standard library provides several tools that do less work than a full sort:</p> <ul class="simple"> <li><p><a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> and <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> return the smallest and largest values, respectively. These functions make a single pass over the input data and require almost no auxiliary memory.</p></li> <li><p><a class="reference internal" href="../library/heapq.html#heapq.nsmallest" title="heapq.nsmallest"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.nsmallest()</span></code></a> and <a class="reference internal" href="../library/heapq.html#heapq.nlargest" title="heapq.nlargest"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.nlargest()</span></code></a> return the <em>n</em> smallest and largest values, respectively. These functions make a single pass over the data keeping only <em>n</em> elements in memory at a time. For values of <em>n</em> that are small relative to the number of inputs, these functions make far fewer comparisons than a full sort.</p></li> <li><p><a class="reference internal" href="../library/heapq.html#heapq.heappush" title="heapq.heappush"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.heappush()</span></code></a> and <a class="reference internal" href="../library/heapq.html#heapq.heappop" title="heapq.heappop"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.heappop()</span></code></a> create and maintain a partially sorted arrangement of data that keeps the smallest element at position <code class="docutils literal notranslate"><span class="pre">0</span></code>. These functions are suitable for implementing priority queues which are commonly used for task scheduling.</p></li> </ul> </section> </section> <div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Sorting Techniques</a><ul> <li><a class="reference internal" href="#sorting-basics">Sorting Basics</a></li> <li><a class="reference internal" href="#key-functions">Key Functions</a></li> <li><a class="reference internal" href="#operator-module-functions-and-partial-function-evaluation">Operator Module Functions and Partial Function Evaluation</a></li> <li><a class="reference internal" href="#ascending-and-descending">Ascending and Descending</a></li> <li><a class="reference internal" href="#sort-stability-and-complex-sorts">Sort Stability and Complex Sorts</a></li> <li><a class="reference internal" href="#decorate-sort-undecorate">Decorate-Sort-Undecorate</a></li> <li><a class="reference internal" href="#comparison-functions">Comparison Functions</a></li> <li><a class="reference internal" href="#odds-and-ends">Odds and Ends</a></li> <li><a class="reference internal" href="#partial-sorts">Partial Sorts</a></li> </ul> </li> </ul> </div> <div> <h4>Previous topic</h4> <p class="topless"><a href="sockets.html" title="previous chapter">Socket Programming HOWTO</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="unicode.html" title="next chapter">Unicode HOWTO</a></p> </div> <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/main/Doc/howto/sorting.rst" rel="nofollow">Show Source </a> </li> </ul> </div> </div> <div id="sidebarbutton" title="Collapse sidebar"> <span>«</span> </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="unicode.html" title="Unicode HOWTO" >next</a> |</li> <li class="right" > <a href="sockets.html" title="Socket Programming HOWTO" >previous</a> |</li> <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.12.3 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> »</li> <li class="nav-item nav-item-this"><a href="">Sorting Techniques</a></li> <li class="right"> <div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" /> <input type="submit" value="Go" /> </form> </div> | </li> <li class="right"> <label class="theme-selector-label"> Theme <select class="theme-selector" oninput="activateTheme(this.value)"> <option value="auto" selected>Auto</option> <option value="light">Light</option> <option value="dark">Dark</option> </select> </label> |</li> </ul> </div> <div class="footer"> © <a href="../copyright.html"> Copyright </a> 2001-2024, Python Software Foundation. <br /> This page is licensed under the Python Software Foundation License Version 2. <br /> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br /> See <a href="/license.html">History and License</a> for more information.<br /> <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> <br /> Last updated on Apr 09, 2024 (13:47 UTC). <a href="/bugs.html">Found a bug</a>? <br /> Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6. </div> </body> </html>
Save