What is the best way of creating an alphabetically sorted list in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to toggle on Order in ReactJS
- How to get the background from multiple images by
- PHP Recursively File Folder Scan Sorted by Modific
Suppose
s = "ZWzaAd"
To sort above string the simple solution will be below one.
The proper way to sort strings is:
The previous example of
mylist.sort(key=lambda x: x.lower())
will work fine for ASCII-only contexts.It really is that simple :)
Please use sorted() function in Python3
Basic answer:
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the
sorted()
function:However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter
key
to specify custom sorting order (the alternative, usingcmp
, is a deprecated solution, as it has to be evaluated multiple times -key
is only computed once per element).So, to sort according to the current locale, taking language-specific rules into account (
cmp_to_key
is a helper function from functools):And finally, if you need, you can specify a custom locale for sorting:
Last note: you will see examples of case-insensitive sorting which use the
lower()
method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data: