Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of tuples by their second elements

I want to sort a list of tuples by their second elements.

Example input:

[("Bob",3),("Terry",1)]

Example output:

[("Terry",1)("Bob",3)]
like image 379
user1214840 Avatar asked Feb 16 '12 21:02

user1214840


People also ask

Can I sort a list of tuples?

By using the sort() method we can easily sort the list of tuples alphabetically. To do this task first we have to create a function and pass the list as an argument. In the sort method, the key parameter is set to sort the element by using the lambda function.

How do you sort a list of tuples based on first value Python?

Using sorted() function or in place sort are the ways to Sort a list of tuples by the first element in Python. Both methods need to use the key keyword. Note: key should be a function that identifies how to retrieve the comparable element from your data structure.

How do you sort two tuples in Python?

Sorting a List by the Second Element of the Tuple. If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key. Unfortunately, Python does not allow you to specify the index of the sorting element directly.


1 Answers

Another cool trick is to use on from Data.Function:

import Data.Function (on)
import Data.List (sortBy)

sortBy (compare `on` snd) [...]

Not much different than comparing but a nice trick from time to time.

like image 199
Daniel Lyons Avatar answered Nov 26 '22 13:11

Daniel Lyons