Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list/tuple of lists/tuples by the element at a given index?

I have some data either in a list of lists or a list of tuples, like this:

data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] 

And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I store tuples or lists in my list?

like image 607
Stan Avatar asked Jun 25 '10 23:06

Stan


People also ask

How do you sort a tuple by index?

Python sort list of tuples by first and second element. To sort the first tuple element we can use an index() method like list[0]. Similar to the second element we can use the list[1] index. By using the sort method we need to sort the lists in place and order.

How do you sort tuples of tuples?

In Python, use the sorted() built-in function to sort a Tuple. The tuple should be passed as an argument to the sorted() function. The tuple items are sorted (by default) in ascending order in the list returned by the function. We can use a tuple to convert this list data type to a tuple ().

Can you sort a list of tuples?

Method #1: Using the Bubble Sort Using the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the second element of each tuple using the nested loops.

How do you sort data in tuple?

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.


1 Answers

sorted_by_second = sorted(data, key=lambda tup: tup[1]) 

or:

data.sort(key=lambda tup: tup[1])  # sorts in place 

The default sort mode is ascending. To sort in descending order use the option reverse=True:

sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True) 

or:

data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place 
like image 114
Stephen Avatar answered Oct 05 '22 08:10

Stephen