Python sorting
If you want a version that return result, use sorted() function.
>>> a = [5, 2, 3, 1, 4] >>> a.sort() # become [1, 2, 3, 4, 5] >>> a.sort(cmp) # same as above >>> a = "This is a test string from Andrew".split() >>> a.sort(key=str.lower) # using key is simpler # ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] >>> import operator >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)] >>> sorted(L, key=operator.itemgetter(1)) [('d', 1), ('c', 2), ('b', 3), ('a', 4)] # itemgetter allows easy Schwartzian transform
3 equivalent ways
- key=operator.itemgetter(1)
- key=lambda x: x[1]
- cmp=lambda a,b: cmp(a[1], b[1])
Learn more at Sorting Howto.