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?
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().
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.
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.
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.
sorted(unsorted, key=lambda element: (element[1], element[2]))
I've assumed an order for the keys from the sample output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With