Mixed order sort with helper function (Python)

vegaseat 3 Tallied Votes 490 Views Share

A Python sort with a helper function to allow for mixed order sort like age descending and weight ascending.

''' sort_helper101.py
use a sort helper function to perform a complex sort
here sort first by age in reverse order (descending, highest age first) 
then by same age weight (ascending, lowest weight first)
tested with Python27 and Python33  by  vegaseat  30oct2013
'''

def sort_helper(tup):
    '''
    helper function for sorting of a list of (name, age, weight) tuples
    sort by looking at age tup[1] first then weight tup[2]
    the minus sign indicates reverse order (descending) sort for age
    '''
    return (-tup[1], tup[2])

# original list of (name, age, weight) tuples
q = [('Tom', 35, 244), ('Joe', 35, 150), ('All', 24, 175), ('Zoe', 35, 210)]

print('Original list of (name, age, weight) tuples:')
print(q)
print('-'*70)
print('List sorted by age (descending) and same age weight (ascending):')
print(sorted(q, key=sort_helper))

# or using lambda as an anonymous helper function 
print(sorted(q, key=lambda tup: (-tup[1], tup[2])))

''' result ...
Original list of (name, age, weight) tuples:
[('Tom', 35, 244), ('Joe', 35, 150), ('All', 24, 175), ('Zoe', 35, 210)]
----------------------------------------------------------------------
List sorted by age (descending) and same age weight (ascending):
[('Joe', 35, 150), ('Zoe', 35, 210), ('Tom', 35, 244), ('All', 24, 175)]
[('Joe', 35, 150), ('Zoe', 35, 210), ('Tom', 35, 244), ('All', 24, 175)]
'''