[Tutor] Sorting
Ben Beuchler
insyte@emt-p.org
Tue, 25 Jan 2000 22:26:57 -0600 (CST)
On Tue, 18 Jan 2000, Daniel Yoo wrote:
> > 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)
I have to admit, the ability to pass extra arguments to x.sort() confuses
me. Can you clarify a little what is happening in that lambda expression
and how it talks sort into dealing with the fourth column instead of the
first?
Thanks,
Ben
--
"There is no spoon"
-- The Matrix