1
1
# Sebastian Raschka 09/02/2014
2
- # Sorting a list of tuples by th
8000
e last elements of the tuple
3
-
2
+ # Sorting a list of tuples by starting with the last element of the tuple (=reversed tuple)
4
3
5
4
# Here, we make use of the "key" parameter of the in-built "sorted()" function
6
5
# (also available for the ".sort()" method), which let's us define a function
9
8
# from every tuple.
10
9
11
10
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' )]
14
12
15
13
sorted_list = sorted (a_list , key = lambda e : e [::- 1 ])
16
14
17
15
print (sorted_list )
18
16
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