Sorting a List


def keySort (x, y):     xIndex = keyList.index(x)     yIndex = keyList.index(y)     return cmp(xIndex, yIndex) letterList.sort() letterList.sort(lambda x, y: keySort(x, y)) caseList.sort() caseList.sort(key=str.lower) letterList.reverse() letterList.sort(reverse=1)

Items in a list can be sorted using the sort() method. The basic sort method takes no arguments and sorts the items based on the total value of each object. The sort method actually modifies the order of the objects in the list itself. This works as a simple and very effective way to sort simple lists.

The sort method can also accept a comparison function as an argument. The comparison function accepts two arguments and must return a 1, 0, or -1 depending on whether the second argument is smaller, the same size, or larger than the first argument.

The sort method can also accept a key function. The key function should accept one argument that will be used to extract a key from each object in the list. That key will be used to sort the list rather than the value of the object itself.

A list can be sorted in reverse order, by passing the keyterm reverse as an argument to the sort method. reverse is a Boolean, and if it is set to true, the list is sorted in reverse order. The reverse keyterm can be used in tandem with comparison and/or key functions.

Note

If you simply need to reverse the order of a list without necessarily sorting it, use the reverse() method. The reverse method accepts no arguments and simply reverses the order of the items in the list.


keyList = ['a', 'c', 'b', 'y', 'z', 'x'] letterList = ['b', 'c', 'a', 'z', 'y', 'x'] caseList = ['d', 'B', 'F', 'A', 'E', 'c'] #Custom sort procedure def keySort (x, y):     xIndex = keyList.index(x)     yIndex = keyList.index(y)     return cmp(xIndex, yIndex) print letterList #Sort the list letterList.sort() print letterList #Custom sort letterList.sort(lambda x, y: keySort(x, y)) print letterList #Key sort print caseList caseList.sort() print caseList caseList.sort(key=str.lower) print caseList #Reverse list letterList.reverse() print letterList #Reverse sort letterList.sort(reverse=1) print letterList


sort_list.py

['b', 'c', 'a', 'z', 'y', 'x'] ['a', 'b', 'c', 'x', 'y', 'z'] ['a', 'c', 'b', 'y', 'z', 'x'] ['d', 'B', 'F', 'A', 'E', 'c'] ['A', 'B', 'E', 'F', 'c', 'd'] ['A', 'B', 'c', 'd', 'E', 'F'] ['x', 'z', 'y', 'b', 'c', 'a'] ['z', 'y', 'x', 'c', 'b', 'a']


Output from sort_list.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net