Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Sort a List Alphabetically in Python?

#1
How to Sort a List Alphabetically in Python?

<div><p><strong>Problem</strong>: Given a list of strings. Sort the list of strings in alphabetical order.</p>
<p><strong>Example: </strong></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="">['Frank', 'Alice', 'Bob'] --> ['Alice', 'Bob', 'Frank']</pre>
<p><strong>Solution</strong>: Use the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" target="_blank">list.sort()</a> method without argument to solve the list in lexicographical order which is a generalization of alphabetical order (also applies to the second, third, … characters). </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 = ['Frank', 'Alice', 'Bob']
lst.sort()
print(lst)
# ['Alice', 'Bob', 'Frank']</pre>
<p><strong>Try It Yourself:</strong></p>
<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-repl-it">
<div class="wp-block-embed__wrapper">
<iframe title="sortalphabet" class="wp-embedded-content" sandbox="allow-scripts" security="restricted" src="https://repl.it/@finxter/sortalphabet?lite=true#?secret=HiPAailwCE" data-secret="HiPAailwCE" width="800" height="600" frameborder="0"></iframe>
</div>
</figure>
<h2>Python List Sort Alphabetically Case Insensitive</h2>
<p>The problem with the default list.sort() or sorted(list) method is that they consider capitalization. This way, it can lead to strange sortings like this:</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 = ['ab', 'Ac', 'ad']
lst.sort()
print(lst)
# ['Ac', 'ab', 'ad']</pre>
<p>Intuitively, you would expect the string <code>'ab'</code> to occur before <code>'Ac'</code>, right?</p>
<p>To ignore the capitalization, you can simply call the <code>x.lower()</code> method on each element <code>x</code> before sorting the list. </p>
<p>However, my preferred method is to use the key argument to accomplish the same thing in a single line of code:</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 = ['ab', 'Ac', 'ad']
lst.sort(key=lambda x: x.lower())
print(lst)
# ['ab', 'Ac', 'ad']</pre>
<p><a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">If you like one-liners, you’ll love my new book “Python One-Liners” with NoStarch Press (Amazon Link</a><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener">)</a><a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">.</a></p>
<h2>Python List Sort Alphabetically Reverse</h2>
<p>You can reverse the order of the list by using the reverse keyword. Set <code>reverse=False</code> to sort in ascending order and set <code>reverse=True</code> to sort in descending order. </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 = ['Frank', 'Alice', 'Bob'] lst.sort(reverse=False)
print(lst)
# ['Alice', 'Bob', 'Frank'] lst.sort(reverse=True)
print(lst)
# ['Frank', 'Bob', 'Alice']</pre>
<h2>Python List Sort Alphabetically and Numerically</h2>
<p><strong>Problem</strong>: You’ve got a list of strings. Each strings contains a number. You want the numbers to sort numerically (e.g. 100 comes <em>after </em>20, not before) but the characters to sort alphabetically (e.g., <code>'c'</code> comes before <code>'d'</code>).</p>
<p><strong>Example</strong>:</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="">['alice 100', 'alice 20', 'bob 99'] --> ['alice 20', 'alice 100', 'bob 99'</pre>
<p><strong>Naive Solution (doesn’t work):</strong> Use the list.sort() method to sort the list alphabetically:</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 = ['alice 100', 'alice 20', 'bob 99']
lst.sort()
print(lst)
# ['alice 100', 'alice 20', 'bob 99']</pre>
<p>Because the number 100 comes before 20 in an alphabetical order, the string <code>'alice 100'</code> is placed before <code>'alice 20'</code>.</p>
<p><strong>Solution</strong>: I found <a href="https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python" target="_blank" rel="noreferrer noopener">this</a> code on StackOverflow that nicely demonstrates how to do this:</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 sorted_nicely(l): """ Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert© for c in re.split('([0-9]+)', key)] l.sort(key = alphanum_key) lst = ['alice 100', 'alice 20', 'bob 99']
sorted_nicely(lst)
print(lst)
# ['alice 20', 'alice 100', 'bob 99']</pre>
<p>The idea is to differentiate characters and numbers and use them as the basis of comparison for the sort routine.</p>
<h2>Where to Go From Here?</h2>
<p><em>The <code>list.sort()</code> method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional <code>key</code> argument by passing a function that returns a comparable value for each element in the list. With the optional Boolean <code>reverse</code> argument, you can switch from ascending (<code>reverse=False</code>) to descending order (<code>reverse=True</code>).</em></p>
<p>If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: <a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Python One-Liners</a> (Amazon Link). </p>
<p>In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!</p>
<p><a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Get the book from Amazon!</a></p>
<p><strong>OFFICIAL BOOK DESCRIPTION:</strong> <em>Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.</em></p>
</div>


https://www.sickgaming.net/blog/2020/03/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016