code_junkie

Sorting a tuple that contains tuples

Nov 11th, 2011
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. MY_TUPLE = (
  2. ('A','Apple'),
  3. ('C','Carrot'),
  4. ('B','Banana'),
  5. )
  6.  
  7. from opererator import itemgetter
  8.  
  9. MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))
  10.  
  11. MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
  12.  
  13. >>> import operator
  14. >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
  15. >>> map(operator.itemgetter(0), L)
  16. ['c', 'd', 'a', 'b']
  17. >>> map(operator.itemgetter(1), L)
  18. [2, 1, 4, 3]
  19. >>> sorted(L, key=operator.itemgetter(1))
  20. [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
  21.  
  22. sorted(my_tuple, key=lambda tup: tup[1])
  23.  
  24. templist = [ (line[1], line) for line in MY_TUPLE ]
  25. templist.sort()
  26. SORTED_MY_TUPLE = [ line[1] for line in templist ]
Add Comment
Please, Sign In to add comment