[Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python (/thread-101250.html) |
[Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python - xSicKxBot - 08-16-2023 [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1550560","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","legendonly":"","readonly":"","score":"5","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","title":"5 Effective Methods to Sort a List of String Numbers Numerically in Python","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div> </p></div> <h2 class="wp-block-heading">Problem Formulation</h2> <p>Sorting a list of string numbers numerically in Python can lead to unexpected issues. </p> <p>For <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/3426108/how-to-sort-a-list-of-strings-numerically" data-type="URL" data-id="https://stackoverflow.com/questions/3426108/how-to-sort-a-list-of-strings-numerically" target="_blank">example</a>, using the naive approach to sort the list <code>lst = ["1", "10", "3", "22", "23", "4", "2", "200"]</code> using <code>lst.sort()</code> will result in the incorrect order as it sorts the list of strings lexicographically, not numerically.</p> <p>In this short article, my goal is to present the <strong>five best methods to correctly sort this list numerically</strong>. My recommended approach is the fifth one, see below. <img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h2 class="wp-block-heading">Method 1: Convert Strings to Integers and Sort</h2> <p>This method involves converting each string in the list to an integer and then sorting them. It’s a direct and simple approach to ensure numerical ordering.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = [int(x) for x in lst] lst.sort() </pre> <p><strong>Output</strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']</code></p> <p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank" rel="noreferrer noopener">Python List Comprehension</a></p> <h2 class="wp-block-heading">Method 2: Using the <code>key</code> Parameter with sort()</h2> <p>This method uses the <code>key</code> parameter with the <code>int</code> function to sort the strings as integers. It allows for numerical comparison without altering the original strings.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst.sort(key=int) </pre> <p><strong>Output</strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']</code></p> <p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/sort-a-list-string-tuple-in-python-sort-sorted/" data-type="post" data-id="1550507" target="_blank" rel="noreferrer noopener">Python <code>list.sort()</code> with key parameter</a></p> <h2 class="wp-block-heading">Method 3: Using the natsort Module</h2> <p>The <code>natsort</code> module provides a natural sorting algorithm, useful for sorting strings that represent numbers. This method can handle more complex string sorting scenarios.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from natsort import natsorted lst = natsorted(lst) </pre> <p><strong>Output</strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']</code></p> <h2 class="wp-block-heading">Method 4: Using Regular Expressions</h2> <p>Using regular expressions, this method can sort strings containing both letters and numbers. It converts the numeric parts into floats for comparison, handling mixed content.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re def sort_human(l): convert = lambda text: float(text) if text.isdigit() else text alphanum = lambda key: [convert© for c in re.split('([-+]?[0-9]*\.?[0-9]*)', key)] l.sort(key=alphanum) return l lst = sort_human(lst) </pre> <p><strong>Output</strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']</code></p> <p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-regex/" target="_blank" rel="noreferrer noopener">Python Regular Expression Superpower</a></p> <h2 class="wp-block-heading">Method 5: Using sorted() with key Parameter (Recommended)</h2> <p>This method combines the simplicity of using the <code>key</code> parameter with the benefit of creating a new sorted list, leaving the original untouched. It’s concise and effective.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = sorted(lst, key=int) </pre> <p><strong>Output</strong>: <code>['1', '2', '3', '4', '10', '22', '23', '200']</code></p> <p><img decoding="async" src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-sorted-function/" data-type="post" data-id="18072" target="_blank" rel="noreferrer noopener">Python <code>sorted()</code> function</a></p> <h2 class="wp-block-heading">Summary – When to Use Which</h2> <ul class="has-global-color-8-background-color has-background"> <li><strong>Method 1</strong>: Converts strings to integers, then sorts. Simple but alters the original list.</li> <li><strong>Method 2</strong>: Uses the <code>key</code> parameter with <code>int</code> for sorting. Preserves the original strings.</li> <li><strong>Method 3</strong>: Utilizes the <code>natsort</code> module. Handles complex scenarios.</li> <li><strong>Method 4</strong>: Employs regular expressions for sorting alphanumeric strings.</li> <li><strong>Method 5 (Recommended)</strong>: Combines the simplicity of using <code>key</code> with <code>sorted()</code>. Preserves the original list and offers concise code.</li> </ul> <h2 class="wp-block-heading">Python One-Liners Book: Master the Single Line First!</h2> <p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p> <div class="wp-block-image"> <figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-300x277.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-768x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure> </div> <p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p> <p>The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p> <p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts </em></strong>and<strong><em> boost your coding and analytical skills</em></strong>. You’ll learn about advanced Python features such as <em><strong>list comprehension</strong></em>, <strong><em>slicing</em></strong>, <strong><em>lambda functions</em></strong>, <strong><em>regular expressions</em></strong>, <strong><em>map </em></strong>and <strong><em>reduce </em></strong>functions, and <strong><em>slice assignments</em></strong>. </p> <p>You’ll also learn how to:</p> <ul> <li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li> <li>Use <strong>NumPy basics</strong> such as <em>array</em>, <em>shape</em>, <em>axis</em>, <em>type</em>, <em>broadcasting</em>, <em>advanced indexing</em>, <em>slicing</em>, <em>sorting</em>, <em>searching</em>, <em>aggregating</em>, and <em>statistics</em></li> <li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li> <li>Create more <strong>advanced regular expressions</strong> using <em>grouping </em>and <em>named groups</em>, <em>negative lookaheads</em>, <em>escaped characters</em>, <em>whitespaces, character sets</em> (and <em>negative characters sets</em>), and <em>greedy/nongreedy operators</em></li> <li>Understand a wide range of <strong>computer science topics</strong>, including <em>anagrams</em>, <em>palindromes</em>, <em>supersets</em>, <em>permutations</em>, <em>factorials</em>, <em>prime numbers</em>, <em>Fibonacci </em>numbers, <em>obfuscation</em>, <em>searching</em>, and <em>algorithmic sorting</em></li> </ul> <p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p> <p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners on Amazon!!</em></a></strong></p> </div> https://www.sickgaming.net/blog/2023/08/06/5-effective-methods-to-sort-a-list-of-string-numbers-numerically-in-python/ |