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?

Problem: Given a list of strings. Sort the list of strings in alphabetical order.

Example:

['Frank', 'Alice', 'Bob'] --> ['Alice', 'Bob', 'Frank']

Solution: Use the list.sort() method without argument to solve the list in lexicographical order which is a generalization of alphabetical order (also applies to the second, third, … characters).

lst = ['Frank', 'Alice', 'Bob']
lst.sort()
print(lst)
# ['Alice', 'Bob', 'Frank']

Try It Yourself:




Python List Sort Alphabetically Case Insensitive


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:

lst = ['ab', 'Ac', 'ad']
lst.sort()
print(lst)
# ['Ac', 'ab', 'ad']

Intuitively, you would expect the string 'ab' to occur before 'Ac', right?

To ignore the capitalization, you can simply call the x.lower() method on each element x before sorting the list.

However, my preferred method is to use the key argument to accomplish the same thing in a single line of code:

lst = ['ab', 'Ac', 'ad']
lst.sort(key=lambda x: x.lower())
print(lst)
# ['ab', 'Ac', 'ad']

If you like one-liners, you’ll love my new book “Python One-Liners” with NoStarch Press (Amazon Link).

Python List Sort Alphabetically Reverse


You can reverse the order of the list by using the reverse keyword. Set reverse=False to sort in ascending order and set reverse=True to sort in descending order.

lst = ['Frank', 'Alice', 'Bob'] lst.sort(reverse=False)
print(lst)
# ['Alice', 'Bob', 'Frank'] lst.sort(reverse=True)
print(lst)
# ['Frank', 'Bob', 'Alice']

Python List Sort Alphabetically and Numerically


Problem: You’ve got a list of strings. Each strings contains a number. You want the numbers to sort numerically (e.g. 100 comes after 20, not before) but the characters to sort alphabetically (e.g., 'c' comes before 'd').

Example:

['alice 100', 'alice 20', 'bob 99'] --> ['alice 20', 'alice 100', 'bob 99'

Naive Solution (doesn’t work): Use the list.sort() method to sort the list alphabetically:

lst = ['alice 100', 'alice 20', 'bob 99']
lst.sort()
print(lst)
# ['alice 100', 'alice 20', 'bob 99']

Because the number 100 comes before 20 in an alphabetical order, the string 'alice 100' is placed before 'alice 20'.

Solution: I found this code on StackOverflow that nicely demonstrates how to do this:

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']

The idea is to differentiate characters and numbers and use them as the basis of comparison for the sort routine.

Where to Go From Here?


The list.sort() method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional key argument by passing a function that returns a comparable value for each element in the list. With the optional Boolean reverse argument, you can switch from ascending (reverse=False) to descending order (reverse=True).

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

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!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: 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.



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



Forum Jump:


Users browsing this thread:
1 Guest(s)

[-]
Discord

[-]
Active Threads
News - Video: Side-By-Side Comparison Of...
Last Post: xSicKxBot
Today 04:07 PM
» Replies: 0
» Views: 2
News - Monster Hunter Stories 2 Is Just ...
Last Post: xSicKxBot
Today 04:07 PM
» Replies: 0
» Views: 2
[Tut] [FIXED] TypeError: string indices ...
Last Post: xSicKxBot
Today 01:14 PM
» Replies: 0
» Views: 2
(Indie Deal) FREE Distortions, Blood Bow...
Last Post: xSicKxBot
Today 01:14 PM
» Replies: 0
» Views: 3
Microsoft - 11 new 3D cities now availab...
Last Post: xSicKxBot
Today 11:30 AM
» Replies: 0
» Views: 4
News - Former Metroid Prime Engineer Adm...
Last Post: xSicKxBot
Today 11:30 AM
» Replies: 0
» Views: 4
Xbox Wire - Psychological Thriller Marth...
Last Post: xSicKxBot
Today 11:30 AM
» Replies: 0
» Views: 2
News - Size up your screen with 50% off ...
Last Post: xSicKxBot
Today 11:30 AM
» Replies: 0
» Views: 4
News - Boost Your IT Skills With 70% Off...
Last Post: xSicKxBot
Today 11:30 AM
» Replies: 0
» Views: 2
News - Black Ops Cold War Launches Doubl...
Last Post: xSicKxBot
Today 07:43 AM
» Replies: 0
» Views: 4

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com



Discord Server © SickGaming.net 2012-2021