# sort a list on your own criteria # define your own method for sorting (must return 1, 0, -1) def mysort(x,y): x = len(x) y = len(y) if x>y: return 1 elif x==y: return 0 else: return -1 alist = ['Here', 'is', 'a', 'list', 'of', 'small', 'and', 'gybungusly', 'big', 'words'] alist.sort(mysort) # the list is now sorted from smallest to largest word print alist #output: # ['a', 'is', 'of', 'and', # 'big', 'Here', 'list', # 'small', 'words', 'gybungusly'] # if your needs just include needing # to sort alphabetically you can use # the typical sort() method #
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Tuesday, September 15, 2009
Python - custom sort a list
Subscribe to:
Post Comments (Atom)
mysort() doesn't sort, it orders. For your general example I would have called it myorder. Then the sort call would read like this:
ReplyDeletealist.sort(myorder)
which I think says what's happening more explicitly.
For this specific case:
alist.sort(orderByLength)