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

Adam Bark adam.jtm30 at gmail.com
Tue Sep 14 03:11:33 CEST 2010


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]

as list indices go [start:end:step] what this means is the whole list 
starting from the end and working backwards.
You can also have a look at reversed() if you want an iterator or you 
can use theList.reverse() if you want to reverse in place ie.

 >>> l = ["21 trewuuioi","3zxc","134445"]
 >>> l.reverse()
 >>> print l
['134445', '3zxc', '21 trewuuioi']


HTH


More information about the Tutor mailing list