How to Sort a List of Tuples with One Key in Reverse Order in Python?

Barbara Streisand
Release: 2024-11-01 17:48:02
Original
880 people have browsed it

How to Sort a List of Tuples with One Key in Reverse Order in Python?

Sorting a List with Two Keys, One in Reverse Order

In Python, sorting a list of tuples by two keys is straightforward. However, there may be cases where you need to sort one key in ascending order and another key in descending order.

Suppose you have a list with tuples like:

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

To sort this list using two keys, you can use sorted():

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

This code sorts the list by the first key in ascending order and the second key in ascending order.

To sort the list in reverse order for one key, you can use a negative sign:

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

Here, the first key is still sorted in ascending order, but the second key is sorted in descending order.

You can try the following code snippets to see the different sorting results:

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

The above is the detailed content of How to Sort a List of Tuples with One Key in Reverse Order 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!