[Tutor] Sorting

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Tue, 18 Jan 2000 13:19:58 -0800 (PST)


> The specific problem I'm facing is that I'm going to be reading in a file
> and using string.split() to turn each line into a list.  This will give me
> a "list of lists". (Is this what other languages call an array?)  I want
> to be able to sort based on any position in a line.  Specifically, I would
> like to be able to sort the entire file based on the same index offset on
> each line.  Effectively sorting based on a specific 'column' in the file.

I believe that you can write a quick lambda expression to use with the
python sort() routine that should work nicely.  Here's an example program
that sorts lines based on the character on the 4 column:

import sys
from string import *
lines = sys.stdin.readlines()
lines.sort(lambda x,y: x[3] > y[3])
for x in lines: print rstrip(x)

There's probably another way to do it... *grin*