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:
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:
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:
Or their third element:
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
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