6.3.3 Sorting listsMethods are provided for sorting data in lists. The simplest of these is the sort() method, which sorts the members into order of ascending value.1 The reverse() method can be used to invert the order of the list afterwards if descending order is wanted. pyxplot> a = [8,4,7,3,6,2] Custom sortingOften, however, a custom ordering is wanted. The sortOn(f) method takes a function of two arguments as its input. The function f(a,b) should return if a is to be placed before b in the sorted list, if a is to be placed after b in the sorted list, and zero if the two elements have equal ranking. The cmp(a,b) function is often useful in making comparison functions for use with the sortOn(f) method: it returns either , or depending on Pyxplot’s default way of comparing two objects. In the example below, we pass it the magnitude of a and b to sort a list in order of magnitude. pyxplot> absCmp(a,b) = cmp(abs(a),abs(b)) In this example, the range(start,end,step) function is used to generate a raster of values between and . It outputs a vector, which is converted into a list using the vector’s list() method. More information about vectors is in Section 6.5. The subroutine command, which is often used to implement more complicated sorting functions, will be covered in Section 7.8. For example, the function used above could have been written: subroutine absCmp(a,b) { return cmp(abs(a),abs(b)) } Sorting lists of listsThe sortOnElement(n) method can be used to sort a list of lists on the th sub-element of each sublist. pyxplot> b = [] Footnotes
|