Sorting in Python

Sometimes you need to order data in your program

Suppose we had the following data:

Archie Ferguson 12 128 St 24 n n

Harcourt Mudd 32 Main St 41 y n

Henry Huggins 47 Klikitat St 10 n y

Thomas Major 14 Venus Way 29 n n

Michael DuMountain 801 Rocky Rd 28 y y

 

How can we sort the records by the homeowner�s last name?

We will use the python sorted()function

It works well and it�s hard to write a better one

sorted() can sort a simple list like this:

>>> sorted(['mary', 'louise', 'bob'])

['bob', 'louise', 'mary']

It can also sort lists that are composed of tuples (here is a default sorting):

>>> tuples = [('mary', 24), ('louise', 48), ('bob', 10)]

>>> sorted(tuples)

[('bob', 10), ('louise', 48), ('mary', 24)]

Or, again using tuples, you can specify which field you want to use for sorting:

>>> sorted(tuples, key=lambda record: record[1]) # sort by age

[('bob', 10), ('mary', 24), ('louise', 48)]

In the last example, sorted() has a �lambda� function option that lets you pick which field to sort on in each tuple

 

How do you get data into tuple format?

The tuple() operator converts a list into a tuple, e.g.:

>>> aList = ['Archie', 'Ferguson', '12', '128', 'St', '24', 'n', 'n']

>>> tuple(aList)

('Archie', 'Ferguson', '12', '128', 'St', '24', 'n', 'n')

 

Now we can sort some data in a record format

 

# Sorting using sample data

# First, read your data into a list separated into tuples.

if __name__ == '__main__':

��� myFile = open('SampleStreetData.txt', 'rt') # open file for reading

��� data = myFile.readlines()������������������ # read whole file into data

��� dataAsListOfTuples = []�������������������� # create an empty list

��� for record in data:������������������������ # look at each line in data

������� print '\nrecord:', record

������� splitRecord = (record.split())��������� # create a space separated list

������� print 'splitRecord:', splitRecord������

������� recordAsTuple = tuple(splitRecord)����� # convert split list into tuple

������� print 'recordAsTuple:', recordAsTuple

������� dataAsListOfTuples.append(recordAsTuple) # store the tuple on the

������������������������������������������������ # empty list we created

 

��� #print 'dataAsListOfTuples', dataAsListOfTuples

��� print '\nUnsorted records within list:'

��� print dataAsListOfTuples

��� print '\nRecords sorted by last name (field 1)'

��� # sort the data by field 1 in each tuple (last name)

��� dataSortedByLastName = sorted(dataAsListOfTuples, key=lambda record: record[1])

��� print dataSortedByLastName