Python Goodies - the sorted function
byon 10-18-2011 at 05:35 PM (5237 Views)
There are so many nice little features of python. Here's a good one to learn; the sorted function.
sorted(iterable[, cmp[, key[, reverse]]]) - http://wiki.python.org/moin/HowTo/Sorting/
This function takes a list and returns a sorted version of the list. That's nice...... but I wouldn't write a blog post about this if that was all this function does. Here's what I really like about the sorted function, the optional key argument. This argument lets you define a function that tells the sorted function what to use to compare different entries in the list.
I recently attended a Rhino python workshop and a student with a background in RhinoScript was putting together a python script that sorted a bunch of curves based on the Z height of each curve's start point. This isn't necessarily hard to do, but it does involve quite a few lines of script to write the sorting routine, and you can potentially write very slow scripts if you aren't careful about your sorting algorithm.
Here's how this script could be written in python using the sorted function along with the key parameter. The function asks you to select a bunch of curves and then adds text dots to the start point of every curve sorted by the curve's start point Z height
import rhinoscriptsyntax as rsdef curvekey(curve):point = rs.CurveStartPoint(curve)return pointdef SortCurvesByZ():curves = rs.GetObjects("Select Curves", rs.filter.curve)if not curves: returnsorted_curves = sorted(curves, key=curvekey)for i, curve in enumerate(sorted_curves):point = rs.CurveStartPoint(curve)rs.AddTextDot(i+1, point)if __name__=="__main__":SortCurvesByZ()
Here's a breakdown of what is happening.
- GetObjects is called so that the user can select a bunch of curves
- Once we a list, we call the sorted function passing the curves and using the named parameter of key=curvekey
- sorted() goes about its job of sorting the list, but since the key parameter was set it knows to call the curvekey function to get a value to use for comparison when sorting.
- We defined curvekey as a function that takes a single input parameter. This is what the key parameter in sorted is expecting; a function that takes a single parameter and returns some sort of value that it knows how to compare. curvekey is called for every item in the list and we return a floating point number (the z height of the start point). The floating point number returned is what sorted uses to compare each item's "value"
- sorted returns a new list of curves that are now in sorted order. We just walk through the new list and add text dots so we can see that things are working.
Pretty darn useful function to keep in your python toolbox!