Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort tuples based on second parameter

I have a list of tuples that look something like this:

("Person 1",10) ("Person 2",8) ("Person 3",12) ("Person 4",20) 

What I want produced, is the list sorted in ascending order, by the second value of the tuple. So L[0] should be ("Person 2", 8) after sorting.

How can I do this? Using Python 3.2.2 If that helps.

like image 356
user974703 Avatar asked Dec 10 '11 19:12

user974703


People also ask

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.

How do you sort a nested tuple?

Sorting Nested Tuples To sort a tuple, we can use sorted() function. This function sorts by default into ascending order. For example, print(sorted(emp)) will sort the tuple 'emp' in ascending order of the 0th element in the nested tuples, i.e. identificaton number.

Does sort () work on tuples?

To sort a Tuple in Python, use sorted() builtin function. Pass the tuple as argument to sorted() function. The function returns a list with the items of tuple sorted in ascending order.


1 Answers

You can use the key parameter to list.sort():

my_list.sort(key=lambda x: x[1]) 

or, slightly faster,

my_list.sort(key=operator.itemgetter(1)) 

(As with any module, you'll need to import operator to be able to use it.)

like image 134
Sven Marnach Avatar answered Sep 23 '22 02:09

Sven Marnach