[Tutor] Sorting a list
Alan Gauld
alan.gauld at btinternet.com
Wed May 13 19:25:16 CEST 2009
"vince spicer" <vinces1979 at gmail.com> wrote
> def compare(x,y):
> try:
> return cmp(int(x), int(y))
> except:
> pass
> try:
> int(x)
> except:
> return -1
> try:
> int(y)
> except:
> return 1
> return 0
Or
def compare(x,y):
if type(x) == str: return -1
if type(y) == str: return 1
return cmp(x,y)
Runs into problems if you have multiple strings and want them
sorted too...
>>> L = [4,3,'word','picture',1,2,3]
>>> sorted(L, cmp=comp)
['picture', 'word', 1, 2, 3, 3, 4]
>>> L = [4,3,'picture','word',1,2,3]
>>> sorted(L, cmp=comp)
['word', 'picture', 1, 2, 3, 3, 4]
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list