# 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.
Showing posts with label custom. Show all posts
Showing posts with label custom. Show all posts
Tuesday, September 15, 2009
Python - custom sort a list
Subscribe to:
Posts (Atom)