comment about reverse

This commit is contained in:
rasbt 2014-08-03 11:32:03 -04:00
parent b87aec3ee9
commit 6e74774e86

View File

@ -1,6 +1,5 @@
# Sebastian Raschka 09/02/2014 # 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 # 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 # (also available for the ".sort()" method), which let's us define a function
@ -9,11 +8,27 @@
# from every tuple. # from every tuple.
a_list = [(1,3,'c'), (2,3,'a'), (3,2,'b'), (2,2,'b')]
a_list = [(1,3,'c'), (2,3,'a'), (1,2,'b')]
sorted_list = sorted(a_list, key=lambda e: e[::-1]) sorted_list = sorted(a_list, key=lambda e: e[::-1])
print(sorted_list) print(sorted_list)
# prints [(2, 3, 'a'), (1, 2, 'b'), (1, 3, 'c')] # 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')]