Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' 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))
- print("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)]
- Using lambda as an anonymous helper function:
- [('Joe', 35, 150), ('Zoe', 35, 210), ('Tom', 35, 244), ('All', 24, 175)]
- '''
Advertisement
Add Comment
Please, Sign In to add comment