Python sorting guide: sorted() function full coverage from entry to advanced usage
0. Write in front
Sorting is an operation that almost all developers use every day - whether it is organizing data reports, filtering Top N results, or beautifying list output, efficient and flexible sorting tools can be of great help.
Python does not let us hand-write these bubbling, fast, and merging algorithms. Instead, it directly builds in the extremely optimized stable sorting algorithm Timsort (default implementation of Python 2.3+), and encapsulates it into the protagonist we are going to talk about today:sorted()。
Next, we will step by step from the most basic integer/string sorting to complex objects, multi-level sorting, and performance optimization scenarios, demonstrating the entire process with reproducible code examples.
1. Basic introduction: sort the sequence directly
sorted()The core advantage lies in its strong versatility - it can accept strings, lists, tuples, generators, etc. all iterable objects, and always returns a new sorted list (the original input will not be modified, very safe!).
1.1 Integer/floating point sorting
By default, the values are sorted from small to large (ascending order):
2. Advanced core: usekeyCustom sorting rules
If "default sorting" is an entry-level operation, then**keyThe parameter** issorted()The soul - it allows us to pass in a function, which will act on each element of the input to generate a "sort by value", and finallysorted()Only the size of these basis values will be compared.
2.1 Simple numerical deformation sorting
For example, sort by absolute value in ascending order:
2.2 Avoiding pitfalls and optimization of string sorting
⚠️ Pitfalls: Sort by ASCII/Unicode code value by default
The Unicode code value of English uppercase and lowercase letters is that uppercase (A-Z: 65-90) is smaller than lowercase (a-z: 97-122), so direct sorting will put all words starting with uppercase at the front:
✅ Optimization: Ignore case sorting
Givekeypassstr.lower()orstr.upper()That’s it (choosing lower is more general, such as handling the upper and lower case of some non-English characters):
3. Commonly used additions:reverse=TrueSort descending
Want to sort from largest to smallest? Add directlyreverse=TrueParameters, simple and direct:
4. Advanced application: complex object sorting
During development, we rarely only sort pure integers/pure strings, but more complex data such as tuple lists, dictionary lists, and custom class instance lists. At this timekeyThe advantages are even more obvious.
First prepare a list of student tuples as test data:
4.1 Sorting tuple lists
Option 1: Customize ordinary functions
For example, sort by name in ascending order (ignoring case):
Option 2: Simplify with lambda expression
ifkeyThe function logic is very simple and can be written in one line. There is no need to define it separately, just uselambdaAnonymous functions are cleaner:
Option 3: UseoperatorModules improve performance
operatorThe module providesitemgetter()、attrgetter()This type of function is specially used to quickly obtain the index value and attribute value of an object. It is 10%-20% faster than lambda expressions (more obvious for large data sets):
4.2 Multi-level sorting
What should you do if you encounter the requirement that "the first priority is in descending order by grades, and the second priority is in ascending order by name"?
In fact, it's very simple - using the bit-by-bit comparison feature of Python tuples (compare the 0th bit first, compare the 1st bit if equal, and so on), givekeyJust return a tuple containing multi-level evidence:
useitemgetter()Multi-level sorting can also be implemented (but it can only handle priorities in the same direction. To mix ascending and descending order, you still need to combine lambda or separate reverse):
5. Performance and stability tips
Although Python's Timsort is already very fast, there are still a few points to pay attention to when processing millions of data:
5.1 Try to useoperatormodule functions
As mentioned earlier,itemgetter()/attrgetter()Faster than lambdas because they are implemented in C and have less interpreter overhead.
5.2 Try to avoid double countingkey
If the same data set needs to be sorted multiple times, don't letsorted()Recalculate each element'skey——Can be precalculated firstkey, save it as a tuple list, and then extract the original data after sorting (this is called the "decoration-sorting-de-decoration" mode. In fact, Timsort has been optimized internally, but it may be more obvious to deal with extremely large lists manually).
5.3 Taking advantage of the stability of Timsort
Python's sorting is stable sorting - if two elementskeyCompletely equal, their relative positions after sorting are consistent with the original list. For example, in the previous test data, both Alice and Bob scored 75. Bob was first in the original list, but the second priority was by name when sorting, so Alice came to the front; if the second priority was removed, the relative position of the original list would be retained:
6. Summary
Pythonsorted()It is a built-in sorting function with comprehensive functions, excellent performance and friendly interface. The core points are as follows:
- High versatility: accept all iterable objects and return a new list (without modifying the original input)
- Soul parameters
key: Pass in the function to customize the sorting basis, supportedlambdasimplify,operatorspeed up - Additional parameters
reverse=True: Quickly implement descending order - Multi-level sorting: Using the bit-by-bit comparison feature of Python tuples
- Stability: equal
keyThe elements retain their original relative positions
Once you master these, 99% of the sorting requirements in daily development can be easily solved ~

