Sort()

Steven Taschuk staschuk at telusplanet.net
Thu Jun 5 14:27:00 EDT 2003


Quoth Turhan Ozen:
  [...]
> Instead of [a1,a2,a3] becoming [a2,a1,a3], I would like the order remain 
> same but
> 
> a1.rank=2
> a2.rank=1
> a3.rank=3
> 
> How can I do this? Does this functionality already exist? If not could 
> you please give me advice on how to implement it? [...]

Create another list containing the same objects, sort that, then
assign the rank attribute according to position in that other list.

    def assignranks(lst):
        sorted = lst[:]
        sorted.sort()
        for i in range(len(sorted)):   # use enumerate() instead in Python 2.3
            sorted[i].rank = i

(Actually in your example above it seems you want .rank = i+1.
But I prefer to stick with zero-based indexing.)

-- 
Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                                          -- Tony Dylan Davis (CKUA)





More information about the Python-list mailing list