Tuesday, September 15, 2009

Python - custom sort a list

# 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
#

1 comment:

  1. mysort() doesn't sort, it orders. For your general example I would have called it myorder. Then the sort call would read like this:

    alist.sort(myorder)

    which I think says what's happening more explicitly.

    For this specific case:

    alist.sort(orderByLength)

    ReplyDelete