From 6e74774e869eb1e2ce6a159af9aa9bda40ec6172 Mon Sep 17 00:00:00 2001 From: rasbt Date: Sun, 3 Aug 2014 11:32:03 -0400 Subject: [PATCH] comment about reverse --- .../sort_list_of_tuples_by_ele.py | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/howtos_as_py_files/sort_list_of_tuples_by_ele.py b/howtos_as_py_files/sort_list_of_tuples_by_ele.py index 845774d..4a94d4b 100644 --- a/howtos_as_py_files/sort_list_of_tuples_by_ele.py +++ b/howtos_as_py_files/sort_list_of_tuples_by_ele.py @@ -1,6 +1,5 @@ # Sebastian Raschka 09/02/2014 -# Sorting a list of tuples by the last elements of the tuple - +# Sorting a list of tuples by starting with the last element of the tuple (=reversed tuple) # Here, we make use of the "key" parameter of the in-built "sorted()" function # (also available for the ".sort()" method), which let's us define a function @@ -9,11 +8,27 @@ # from every tuple. - -a_list = [(1,3,'c'), (2,3,'a'), (1,2,'b')] +a_list = [(1,3,'c'), (2,3,'a'), (3,2,'b'), (2,2,'b')] sorted_list = sorted(a_list, key=lambda e: e[::-1]) print(sorted_list) -# prints [(2, 3, 'a'), (1, 2, 'b'), (1, 3, 'c')] \ No newline at end of file +# prints [(2, 3, 'a'), (2, 2, 'b'), (3, 2, 'b'), (1, 3, 'c')] + + + +# If we are only interesting in sorting the list by the last element +# of the tuple and don't care about a "tie" situation, we can also use +# the index of the tuple item directly instead of reversing the tuple +# for efficiency. + + + +a_list = [(1,3,'c'), (2,3,'a'), (3,2,'b'), (2,2,'b')] + +sorted_list = sorted(a_list, key=lambda e: e[-1]) + +print(sorted_list) + +# prints [(2, 3, 'a'), (3, 2, 'b'), (2, 2, 'b'), (1, 3, 'c')] \ No newline at end of file