vegaseat

sorting with helper functions

Mar 13th, 2015
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. ''' sort_helper101.py
  2. use a sort helper function to perform a complex sort
  3. here sort first by age in reverse order (descending, highest age first)
  4. then by same age weight (ascending, lowest weight first)
  5. tested with Python27 and Python33  by  vegaseat  30oct2013
  6. '''
  7.  
  8. def sort_helper(tup):
  9.     '''
  10.    helper function for sorting of a list of (name, age, weight) tuples
  11.    sort by looking at age tup[1] first then weight tup[2]
  12.    the minus sign indicates reverse order (descending) sort for age
  13.    '''
  14.     return (-tup[1], tup[2])
  15.  
  16. # original list of (name, age, weight) tuples
  17. q = [('Tom', 35, 244), ('Joe', 35, 150), ('All', 24, 175), ('Zoe', 35, 210)]
  18.  
  19. print('Original list of (name, age, weight) tuples:')
  20. print(q)
  21. print('-'*70)
  22. print('List sorted by age (descending) and same age weight (ascending):')
  23. print(sorted(q, key=sort_helper))
  24.  
  25. print("Using lambda as an anonymous helper function:")
  26. print(sorted(q, key=lambda tup: (-tup[1], tup[2])))
  27.  
  28. ''' result ...
  29. Original list of (name, age, weight) tuples:
  30. [('Tom', 35, 244), ('Joe', 35, 150), ('All', 24, 175), ('Zoe', 35, 210)]
  31. ----------------------------------------------------------------------
  32. List sorted by age (descending) and same age weight (ascending):
  33. [('Joe', 35, 150), ('Zoe', 35, 210), ('Tom', 35, 244), ('All', 24, 175)]
  34. Using lambda as an anonymous helper function:
  35. [('Joe', 35, 150), ('Zoe', 35, 210), ('Tom', 35, 244), ('All', 24, 175)]
  36. '''
Advertisement
Add Comment
Please, Sign In to add comment