Sorting Lists of Strings in Python
One of the common tasks in programming is sorting text data. In Python, sorting a list of strings can be achieved using various techniques.
Basic Sorting
The simplest method is to use the sort() method on the list itself. This sorts the list in-place, modifying the original order.
mylist = ["b", "C", "A"] mylist.sort()
Sorted Copy
If you want to create a sorted copy of the list without modifying the original, use the sorted() function.
for x in sorted(mylist): print(x)
Locale-Sensitive Sorting
By default, Python performs a case-sensitive, ASCII-only sort. To consider locale-specific rules, use the key parameter with the cmp_to_key() helper from functools.
import locale from functools import cmp_to_key sorted(mylist, key=cmp_to_key(locale.strcoll))
Custom Locale Sorting
You can specify a custom locale for sorting. For example, to sort according to English rules with UTF-8 encoding:
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # ...
Case-Insensitive Sorting
Avoid using methods like lower() for case-insensitive sorting because they only work for ASCII characters. Instead, utilize locale-sensitive sorting with tools like strcoll().
Incorrect Case-Insensitive Sorting
# Incorrect because it uses lower(), which is limited to ASCII mylist.sort(key=lambda x: x.lower())
The above is the detailed content of How to Sort Lists of Strings in Python: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!