[Tutor] How to numerically sort strings that start with numbers?

Steven D'Aprano steve at pearwood.info
Tue Sep 14 13:32:23 CEST 2010


On Tue, 14 Sep 2010 11:11:33 am Adam Bark wrote:
> On 14/09/10 01:11, Pete O'Connell wrote:
> > theList = ["21 trewuuioi","3zxc","134445"]
> > print sorted(theList)
> >
> > Hi, the result of the sorted list above doesn't print in the order
> > I want. Is there a straight forward way of getting python to print
> > ['3zxc','21 trewuuioi','134445']
> > rather than ['134445', '21 trewuuioi', '3zxc']?
> >
> > Any help would be greatly appreciated
> > Pete
>
> print sorted(theList)[::-1]

That's a very inefficient way of doing it. First it makes a copy of the 
list, then it sorts it, then it makes *another* copy in reverse.

A better way is:

sorted(theList, reverse=True)



-- 
Steven D'Aprano


More information about the Tutor mailing list