Home > Backend Development > Python Tutorial > How to Reverse the Sort Order for Specific Keys in Python\'s `sorted()` Function?

How to Reverse the Sort Order for Specific Keys in Python\'s `sorted()` Function?

Susan Sarandon
Release: 2024-11-02 17:38:29
Original
516 people have browsed it

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)]
Copy after login

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]))
Copy after login

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)
Copy after login

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]))
Copy after login

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]))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template