How to Sort Lists With Multiple Keys, Including Reverse Ordering in Python?

Susan Sarandon
Release: 2024-11-02 05:58:03
Original
738 people have browsed it

How to Sort Lists With Multiple Keys, Including Reverse Ordering in Python?

Sorting Lists with Multiple Keys, Including Reverse Ordering

Python provides the sorted() function for sorting lists. To sort by multiple keys, a lambda function can be used as the key argument. However, when sorting with multiple keys, all keys are sorted in ascending order by default.

Consider a list of tuples:

<code class="python">myList = [(ele1A, ele2A), (ele1B, ele2B), (ele1C, ele2C)]</code>
Copy after login

To sort this list using both keys, the following code can be used:

<code class="python">sortedList = sorted(myList, key=lambda y: (y[0].lower(), y[1]))</code>
Copy after login

This code sorts the elements in ascending order by the first key and then by the second key in ascending order. To sort in reverse order with one key, the lambda function can be modified:

<code class="python">sortedList = sorted(myList, key=lambda y: (y[0].lower(), -y[1]))</code>
Copy after login

In this example, the negative sign before y[1] reverses the sorting order for the second key. However, this code will sort all elements in reverse order by the second key.

To sort in reverse order by one key and ascending order by the other, the following code can be used:

<code class="python">sortedList = sorted(myList, key=lambda y: (-y[0].lower(), y[1]))</code>
Copy after login

Here, the negative sign is used with the first key to reverse the sorting order for the first key.

The above is the detailed content of How to Sort Lists With Multiple Keys, Including Reverse Ordering in Python?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!