D'oh! Once again I've presented a simplified example which has a
simple answer. The real problem involves sorting strings in the form
"digits[:digits[[-|;]digits]] other stuff" where each substring of digits
is to be treated as a number. I didn't want to clutter up the mailing list
with 41 lines of code. The answer to my problem seems to be "convert
whatever you've got to a tuple of components with which sort will do
the right thing". Thanks for the comments which lead to that epiphany!
BTW, here's the code I didn't show. If I had taken time to refactor this
as shown further below, I would have realized the "parts" function works
as the key. Your responses always prove to be enlightening.
Oh, and the ActiveState reference is a great help. It'll be the technique
to use when "convert to tuple" technique doesn't apply.
############# the naive (and ugly) version ###############
def cmp_fns(a,b):
a = a.split()[0]
try:
a1,a2 = a.split(':')
except:
a1 = a; a2 = "0"
try:
a2,a2v = a2.split('-')
except:
try:
a2,a2v = a2.split(';')
except:
a2v=""
b = b.split()[0]
try:
b1,b2 = b.split(':')
except:
b1 = b; b2 = "0"
try:
b2,b2v = b2.split('-')
except:
try:
b2,b2v = b2.split(';')
except:
b2v=""
if a1 < b1:
return -1
elif a1 > b1:
return 1
else:
if int(a2) < int(b2):
return -1
elif int(a2) < int(b2):
return 1
else:
if a2v < b2v:
return -1
elif a2v > b2v:
return 1
else:
return 0
############# the refactored version ###############
def parts(x):
x1 = x.split()[0]
if x1.find(':') >= 0:
x1,x2 = x1.split(':')
if x2.find('-') >= 0:
x2,x2v = x2.split('-')
elif x2.find(';') >= 0:
x2,x2v = x2.split(';')
else:
x2v="0"
else
x2 = "0"
x2v="0"
return(int(x1),int(x2),int(x2v))
def cmp_fns(a,b):
A = parts(a)
B = parts(b)
if A < B:
return -1
elif A > B:
return 1
else:
return 0
--
Randolph Bentson
[email protected]