Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of tuples depending on two elements [duplicate]

Possible Duplicate:
python: how to sort a complex list on two different keys

I've got a list of tuples. I want to sort them depending two elements. Here is following example

unsorted = [('a', 4, 2), ('a', 4, 3), ('a', 7, 2), ('a', 7, 3), ('b', 4, 2), ('b', 4, 3), ('b', 7, 2), ('b', 7, 3)] sorted   = [('a', 4, 2), ('b', 4, 2), ('a', 4, 3), ('b', 4, 3), ('a', 7, 2), ('b', 7, 2), ('a', 7, 3), ('b', 7, 3)] 

I know how to sort them on the second element:

sorted(unsorted, key = lambda element : element[1]) 

But how to do that with two keys?

like image 398
Razer Avatar asked Feb 21 '12 11:02

Razer


People also ask

How do you sort a list of tuples based on two values?

In python, if you want to sort a list of tuples by the second element then we have the function called sort() and by using lambda function as a key function. A custom comparator is a key function in sort().

How do you sort a list of tuples?

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.

How do you sort a tuple in Python without sorting?

You can use one of the easiest sorting algorithm that is bubble sort. In case of tuples in tuple it will sort in order of first element of tuple. So ((32, "b"), (1, "c"), (23,"a")) Now if you sort it it will sort it in the order of 1st element of tuple.

How does sorted sort tuples?

A tuple is a data type for immutable ordered sequences of elements. To sort elements of a tuple, we can use the sorted function, providing the tuple as the first argument. This function returns a sorted list from the given iterable, and we can easily convert this list into a tuple using the built-in function tuple.


1 Answers

sorted(unsorted, key=lambda element: (element[1], element[2])) 

I've assumed an order for the keys from the sample output.

like image 179
Michael J. Barber Avatar answered Sep 29 '22 08:09

Michael J. Barber