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.

2 comments:

Anonymous said...

You can also supply a SQL postfix clause to the cursor to do an ORDERBY. When working with Geodatabase tables/feature classes and you want to sort on a field, always use ORDERBY as it will be much faster.


with arcpy.da.SearchCursor("cities", ("OID@", "NAME", "STATE", "SHAPE@XY"), sql_clause=(None,"ORDER BY name")) as rows:

Andrew said...

Very good tip, but this method allows you to sort on the fly.