11# Sebastian Raschka 09/02/2014
2- # Sorting a list of tuples by the last elements of the tuple
3-
2+ # Sorting a list of tuples by starting with the last element of the tuple (=reversed tuple)
43
54# Here, we make use of the "key" parameter of the in-built "sorted()" function
65# (also available for the ".sort()" method), which let's us define a function
98# from every tuple.
109
1110
12-
13- a_list = [(1 ,3 ,'c' ), (2 ,3 ,'a' ), (1 ,2 ,'b' )]
11+ a_list = [(1 ,3 ,'c' ), (2 ,3 ,'a' ), (3 ,2 ,'b' ), (2 ,2 ,'b' )]
1412
1513sorted_list = sorted (a_list , key = lambda e : e [::- 1 ])
1614
1715print (sorted_list )
1816
19- # prints [(2, 3, 'a'), (1, 2, 'b'), (1, 3, 'c')]
17+ # prints [(2, 3, 'a'), (2, 2, 'b'), (3, 2, 'b'), (1, 3, 'c')]
18+
19+
20+
21+ # If we are only interesting in sorting the list by the last element
22+ # of the tuple and don't care about a "tie" situation, we can also use
23+ # the index of the tuple item directly instead of reversing the tuple
24+ # for efficiency.
25+
26+
27+
28+ a_list = [(1 ,3 ,'c' ), (2 ,3 ,'a' ), (3 ,2 ,'b' ), (2 ,2 ,'b' )]
29+
30+ sorted_list = sorted (a_list , key = lambda e : e [- 1 ])
31+
32+ print (sorted_list )
33+
34+ # prints [(2, 3, 'a'), (3, 2, 'b'), (2, 2, 'b'), (1, 3, 'c')]
0 commit comments