Thursday, May 17, 2012

Sorting a List of Lists

In 10.1, the new arcpy.da (new cursor functions) returns essentially a list of lists.  A way to sort these list of lists is to use sorted() which is a built in function of python.  More can be found here.

Here is a simple example, but I think it will get what you need.


>>> myresults = [
[1,"A",2],
[2,"Z",1],
[3,"J",0]
]
>>> print sorted(myresults, key=lambda x:x[0])
[[1, 'A', 2], [2, 'Z', 1], [3, 'J', 0]]
>>> print sorted(myresults, key=lambda x:x[1])
[[1, 'A', 2], [3, 'J', 0], [2, 'Z', 1]]
>>> print sorted(myresults, key=lambda x:x[2])
[[3, 'J', 0], [2, 'Z', 1], [1, 'A', 2]]

Here we have our list with 3 entries in each sub-list item. The lambda function tells the sorted() what to sort on. The numeric value is the position in the sub-list item inside the parent list.