Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?
Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.
If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?
Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.
Use sorted() and str. join() to sort a string alphabetically in Python. Another alternative is to use reduce() method. It applies a join function on the sorted list using the '+' operator.
You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.
IBM's ICU library does that (and a lot more). It has Python bindings: PyICU.
Update: The core difference in sorting between ICU and locale.strcoll
is that ICU uses the full Unicode Collation Algorithm while strcoll
uses ISO 14651.
The differences between those two algorithms are briefly summarized here: http://unicode.org/faq/collation.html#13. These are rather exotic special cases, which should rarely matter in practice.
>>> import icu # pip install PyICU >>> sorted(['a','b','c','ä']) ['a', 'b', 'c', 'ä'] >>> collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8')) >>> sorted(['a','b','c','ä'], key=collator.getSortKey) ['a', 'ä', 'b', 'c']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With