mylist = [["derp", 1, 7], ["bleh", 2, 0], ["merp", 0, 3]]
By default when we call the sort function on this list it will sort the sublists based on their first element in lexicographic order. For example:
mylist.sort()
print mylist
[['bleh', 2, 0], ['derp', 1, 7], ['merp', 0, 3]]
What if we don't want to sort these lists based on their first element though? By using the key argument we can sort our sublists based on any element we want. For example to sort the lists based on their second element we would use:
mylist.sort(key=lambda e: e[1])
print mylist
[['merp', 0, 3], ['derp', 1, 7], ['bleh', 2, 0]]
Or their third element:
mylist.sort(key=lambda e: e[2])
print mylist
[['bleh', 2, 0], ['merp', 0, 3], ['derp', 1, 7]]
Special thanks to the folks over at #python on freenode for helping me figure this little bit out. They are an extremely resourceful bunch. You can learn more about working with python lists here.
Cheers,
~Jeff Hoogland
0 comments:
Post a Comment