Sorting Lists of Strings in Python
One of the common tasks in programming is sorting a list of strings. In Python, there are several ways to achieve this, each with its own merits and caveats.
In-Place Sorting
The simplest approach is to use the sort() method directly on the list. This modifies the original list, sorting its elements alphabetically in-place. However, this approach is not ideal if you want to preserve the original order of the list.
mylist = ["b", "C", "A"] mylist.sort()
Creating Sorted Copies
To obtain a sorted copy of a list without modifying the original, use the sorted() function:
for x in sorted(mylist): print(x)
Locale-Aware Sorting
The sorting methods described above perform case-sensitive, non-locale-aware sorting. To account for locale-specific rules, you can use the key parameter of the sort() or sorted() functions, along with the cmp_to_key() helper function from the functools module:
sorted(mylist, key=cmp_to_key(locale.strcoll))
This will sort the list according to the current locale settings.
Custom Locales
Finally, if you need to specify a custom locale for sorting, use the setlocale() function from the locale module:
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') sorted((u'Ab', u'ad', u'aa'), key=cmp_to_key(locale.strcoll))
The above is the detailed content of How to Sort Strings in Python: In-Place, Copies, Locale-Aware, and Custom Locales?. For more information, please follow other related articles on the PHP Chinese website!