Home > Article > Backend Development > How to Reverse the Sort Order for Specific Keys in Python\'s `sorted()` Function?
Sorting a List with Multiple Keys in Python: One in Reverse Order
When organizing a list with multiple criteria, Python's built-in sorted() function provides a versatile tool. However, it may not always fulfill the requirement of reversing the sort order for a specific key.
Understanding the Issue
Consider a scenario where we have a list of tuples containing two elements:
myList = [(ele1A, ele2A),(ele1B, ele2B),(ele1C, ele2C)]
We may wish to sort this list using two keys: one being case-insensitive (y[0].lower()) and the other in reverse order (y[1]). Using the following code achieves the former:
sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]))
However, to reverse the sort order, we can add the reverse = True argument:
sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]), reverse = True)
Unfortunately, this would reverse the sort order for both keys.
Resolving the Issue
To cater for this requirement, we can leverage the power of lambda functions in Python. By introducing a negative sign (-) before one of the sort key terms, we effectively reverse the sort order for that particular key. For instance:
sortedList = sorted(myList, key = lambda y: (y[0].lower(), -y[1]))
In this code, the -y[1] reverses the sort order for the second key (y[1]), while the first key (y[0].lower()) remains in ascending order case-insensitively.
Additional Examples
Here are some further examples with different combinations of sort orders:
# Reverse both keys sortedList = sorted(myList, key = lambda y: (-y[0].lower(), -y[1])) # Reverse only the first key sortedList = sorted(myList, key = lambda y: (-y[0].lower(), y[1]))
The above is the detailed content of How to Reverse the Sort Order for Specific Keys in Python\'s `sorted()` Function?. For more information, please follow other related articles on the PHP Chinese website!