Thursday, June 6, 2013

Python - Sorting Lists inside of Lists

In some recent python code I was playing with I had the need to sort a bunch of lists based on elements within their elements. Thankfully python's built in sort function is plenty powerful and allows us to do this in a fairly easy manner. So for example if we have a list all of whose elements are also lists:

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:

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.

~Jeff Hoogland

1 comment:

  1. python + lambda functions. These have to be, in my opinion, one of the most powerful features for customizing a wide variety of behaviors that I use on a regular basis.

    At times it feels a bit hackish, but once you get used to how to write a few basics and where you can place them they can make your code simpler and easier to follower by an outside observer.

    They are great for such things such as sorts's key parameter. One can even define that to be just accessing a certain element, like you show above, or some implicit function that operates over the list - such as maybe the measure of a 3-vector, or the mean value of some data.

    Thanks for bringing a trick like this up and showing a few people who may not have known to look for it.