On Jun 14, 12:00 pm, jim-on-linux <[EMAIL PROTECTED]> wrote:
> On Saturday 14 June 2008 03:15, Beema
>
> shafreen wrote:
> > Hi all,
>
> > I have a file with three columns  i need
> > to sort the file with respect to the third
> > column. How do I do it uisng python. I
> > used Linux command to do this. Sort but i
> > not able to do it ? can any body ssuggest
> > me
>
> I have used this method to solve similar
> problems.
>
> This is a consept of how to do what you want,
> but you will have to work a little to get it
> right.
>
> You might try something like this;
>
> Dict = {}  ##create a dictionary
>
> make a list of all column3 values
>
> for loop colum3 values
>
> Make these values the key in a dictionary
> If the values are long, you can use the first
> 7 to 15 characters if you want.
>
> use this key to equal all the values in the
> other columns on the same row.
>
> Dict[column3] = column1, column2, column3
>
> once the dictionary is made
>
> get the dictionary key
> x = Dict.keys()  ## get the keys from Dict
>
> x.sort()  # produce a sorted list of keys of
> column3
>
> Loop these sorted keys to extract from the
> dictionary the values related to each
>
> jim-on-linux
> http://:inqvista.com


Here's another way to attack it. Make a class that takes your columns
as arguments. define an operator on that class to get the comparison
you want. make a list that is your rows, and call sort. here's an
example using only two columns

class twoColumns :
    def __init__(self, c1 = 0, c2 = 0) :
        self.c1 = c1
        self.c2 = c2

    #just use this for debugging if you want to see everything
    def getVals(self):
        print self.c1, self.c2

    #order members of this class by the second column
    def __lt__(c,d):
        if (c.c2 < d.c2) :
            return 1
        else :
            return 0

#end class definition

Here's what happened when I used this class.

>>> r1 = twoColumns(3,4)
>>> r2 = twoColumns(1,5)
>>> test = [r1,r2]  #this is already sorted
>>> test[0].getVals()
3 4
>>> test[1].getVals()
1 5
>>> test.sort() #and the sort looks the same
>>> test[0].getVals()
3 4
>>> test[1].getVals()
1 5
>>> test = [r2,r1]  #I reversed the rows
>>> test[0].getVals()
1 5
>>> test[1].getVals()
3 4
>>> test.sort()  #and we get what we want
>>> test[0].getVals()
3 4
>>> test[1].getVals()
1 5

I think that does what you're asking.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to