While working on a problem from Google Python class, I formulated following result by using 2-3 examples from Stack overflow-
def sort_last(tuples):
return [b for a,b in sorted((tup[1], tup) for tup in tuples)]
print sort_last([(1, 3), (3, 2), (2, 1)])
I learned List comprehension yesterday, so know a little about list comprehension but I am confused how this solution is working overall. Please help me to understand this (2nd line in function).
That pattern is called decorate-sort-undecorate.
(1, 3)into(3, (1, 3)), wrapping eachtuplein a new tuple, with the item you want to sort by first.tupleensuring that the second item in the originaltupleis sorted on first.(3, (1, 3))to(1, 3)while maintaining the order of the list.In Python, explicitly decorating is almost always unnecessary. Instead, use the
keyargument ofsorted:Or, if you want to sort on the reversed version of the
tuple, no matter its length: